ThreadPoolExecutor – Java Thread Pool Example(java线程池创建和使用)
Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed. We can use ThreadPoolExecutor
to create thread pool in java.
Java thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue. java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java. Let’s write a simple program to explain it’s working.
First we need to have a Runnable class, named WorkerThread.java
Copy
package com.journaldev.threadpool;
public class WorkerThread implements Runnable {
<span class="hljs-keyword">private</span> String command;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">WorkerThread</span><span class="hljs-params">(String s)</span></span>{
<span class="hljs-keyword">this</span>.command=s;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
System.out.println(Thread.currentThread().getName()+<span class="hljs-string">" Start. Command = "</span>+command);
processCommand();
System.out.println(Thread.currentThread().getName()+<span class="hljs-string">" End."</span>);
}
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">processCommand</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">try</span> {
Thread.sleep(<span class="hljs-number">5000</span>);
} <span class="hljs-keyword">catch</span> (InterruptedException e) {
e.printStackTrace();
}
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span></span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.command;
}
}
ExecutorService Example
Here is the test program class SimpleThreadPool.java
, where we are creating fixed thread pool from Executors framework.
Copy
package com.journaldev.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleThreadPool {
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
ExecutorService executor = Executors.newFixedThreadPool(<span class="hljs-number">5</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">10</span>; i++) {
Runnable worker = <span class="hljs-keyword">new</span> WorkerThread(<span class="hljs-string">""</span> + i);
executor.execute(worker);
}
executor.shutdown();
<span class="hljs-keyword">while</span> (!executor.isTerminated()) {
}
System.out.println(<span class="hljs-string">"Finished all threads"</span>);
}
}
In above program, we are creating fixed size thread pool of 5 worker threads. Then we are submitting 10 jobs to this pool, since the pool size is 5, it will start working on 5 jobs and other jobs will be in wait state, as soon as one of the job is finished, another job from the wait queue will be picked up by worker thread and get’s executed.
Here is the output of the above program.
Copy
pool-1-thread-2 Start. Command = 1
pool-1-thread-4 Start. Command = 3
pool-1-thread-1 Start. Command = 0
pool-1-thread-3 Start. Command = 2
pool-1-thread-5 Start. Command = 4
pool-1-thread-4 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-3 Start. Command = 8
pool-1-thread-2 End.
pool-1-thread-2 Start. Command = 9
pool-1-thread-1 Start. Command = 7
pool-1-thread-5 Start. Command = 6
pool-1-thread-4 Start. Command = 5
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-3 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
Finished all threads
The output confirms that there are five threads in the pool named from “pool-1-thread-1” to “pool-1-thread-5” and they are responsible to execute the submitted tasks to the pool.
ThreadPoolExecutor Example
Executors class provide simple implementation of ExecutorService using ThreadPoolExecutor but ThreadPoolExecutor provides much more feature than that. We can specify the number of threads that will be alive when we create ThreadPoolExecutor instance and we can limit the size of thread pool and create our own RejectedExecutionHandler implementation to handle the jobs that can’t fit in the worker queue.
Here is our custom implementation of RejectedExecutionHandler interface.
Copy
package com.journaldev.threadpool;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">rejectedExecution</span><span class="hljs-params">(Runnable r, ThreadPoolExecutor executor)</span> </span>{
System.out.println(r.toString() + <span class="hljs-string">" is rejected"</span>);
}
}
ThreadPoolExecutor
provides several methods using which we can find out the current state of executor, pool size, active thread count and task count. So I have a monitor thread that will print the executor information at certain time interval.
Copy
package com.journaldev.threadpool;
import java.util.concurrent.ThreadPoolExecutor;
public class MyMonitorThread implements Runnable
{
private ThreadPoolExecutor executor;
private int seconds;
private boolean run=true;
public MyMonitorThread(ThreadPoolExecutor executor, int delay)
{
this.executor = executor;
this.seconds=delay;
}
public void shutdown(){
this.run=false;
}
@Override
public void run()
{
while(run){
System.out.println(
String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
this.executor.getPoolSize(),
this.executor.getCorePoolSize(),
this.executor.getActiveCount(),
this.executor.getCompletedTaskCount(),
this.executor.getTaskCount(),
this.executor.isShutdown(),
this.executor.isTerminated()));
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Here is the thread pool implementation example using ThreadPoolExecutor.
Copy
package com.journaldev.threadpool;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class WorkerPool {
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String args[])</span> <span class="hljs-keyword">throws</span> InterruptedException</span>{
<span class="hljs-comment">//RejectedExecutionHandler implementation</span>
RejectedExecutionHandlerImpl rejectionHandler = <span class="hljs-keyword">new</span> RejectedExecutionHandlerImpl();
<span class="hljs-comment">//Get the ThreadFactory implementation to use</span>
ThreadFactory threadFactory = Executors.defaultThreadFactory();
<span class="hljs-comment">//creating the ThreadPoolExecutor</span>
ThreadPoolExecutor executorPool = <span class="hljs-keyword">new</span> ThreadPoolExecutor(<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">10</span>, TimeUnit.SECONDS, <span class="hljs-keyword">new</span> ArrayBlockingQueue<Runnable>(<span class="hljs-number">2</span>), threadFactory, rejectionHandler);
<span class="hljs-comment">//start the monitoring thread</span>
MyMonitorThread monitor = <span class="hljs-keyword">new</span> MyMonitorThread(executorPool, <span class="hljs-number">3</span>);
Thread monitorThread = <span class="hljs-keyword">new</span> Thread(monitor);
monitorThread.start();
<span class="hljs-comment">//submit work to the thread pool</span>
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>; i<<span class="hljs-number">10</span>; i++){
executorPool.execute(<span class="hljs-keyword">new</span> WorkerThread(<span class="hljs-string">"cmd"</span>+i));
}
Thread.sleep(<span class="hljs-number">30000</span>);
<span class="hljs-comment">//shut down the pool</span>
executorPool.shutdown();
<span class="hljs-comment">//shut down the monitor thread</span>
Thread.sleep(<span class="hljs-number">5000</span>);
monitor.shutdown();
}
}
Notice that while initializing the ThreadPoolExecutor, we are keeping initial pool size as 2, maximum pool size to 4 and work queue size as 2. So if there are 4 running tasks and more tasks are submitted, the work queue will hold only 2 of them and rest of them will be handled by RejectedExecutionHandlerImpl
.
Here is the output of above program that confirms above statement.
Copy
pool-1-thread-1 Start. Command = cmd0
pool-1-thread-4 Start. Command = cmd5
cmd6 is rejected
pool-1-thread-3 Start. Command = cmd4
pool-1-thread-2 Start. Command = cmd1
cmd7 is rejected
cmd8 is rejected
cmd9 is rejected
[monitor] [0/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
pool-1-thread-4 End.
pool-1-thread-1 End.
pool-1-thread-2 End.
pool-1-thread-3 End.
pool-1-thread-1 Start. Command = cmd3
pool-1-thread-4 Start. Command = cmd2
[monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false
pool-1-thread-1 End.
pool-1-thread-4 End.
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true
Notice the change in active, completed and total completed task count of the executor. We can invoke shutdown() method to finish execution of all the submitted tasks and terminate the thread pool.
If you want to schedule a task to run with delay or periodically then you can use ScheduledThreadPoolExecutor class. Read more about them at Java Schedule Thread Pool Executor.
If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my articles directly. Recently I started creating video tutorials too, so do check out my videos on Youtube.
About Pankaj
ThreadPoolExecutor – Java Thread Pool Example(java线程池创建和使用)的更多相关文章
- Smart Thread Pool (智能线程池)
STPStartInfo stp = new STPStartInfo(); stp.DisposeOfStateObjects = true; stp.CallToPostExecute = ...
- Java并发(四)线程池使用
上一篇博文介绍了线程池的实现原理,现在介绍如何使用线程池. 目录 一.创建线程池 二.向线程池提交任务 三.关闭线程池 四.合理配置线程池 五.线程池的监控 线程池创建规范 一.创建线程池 我们可以通 ...
- ThreadPoolExecutor – Java Thread Pool Example(如何使用Executor框架创建一个线程池)
Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to ...
- Java线程池ThreadPoolExecutor使用和分析(三) - 终止线程池原理
相关文章目录: Java线程池ThreadPoolExecutor使用和分析(一) Java线程池ThreadPoolExecutor使用和分析(二) - execute()原理 Java线程池Thr ...
- ThreadPoolExecutor – Java Thread Pool Example
https://www.journaldev.com/1069/threadpoolexecutor-java-thread-pool-example-executorservice Java t ...
- java多线程(四)-自定义线程池
当我们使用 线程池的时候,可以使用 newCachedThreadPool()或者 newFixedThreadPool(int)等方法,其实我们深入到这些方法里面,就可以看到它们的是实现方式是这样的 ...
- Java并发(六)线程池监控
目录 一.线程池监控参数 二.线程池监控类 三.注意事项 在上一篇博文中,我们介绍了线程池的基本原理和使用方法.了解了基本概念之后,我们可以使用 Executors 类创建线程池来执行大量的任务,使用 ...
- Java并发(三)线程池原理
Java中的线程池是运用场景最多的并发框架,几乎所有需要异步或并发执行任务的程序都可以使用线程池.在开发过程中,合理地使用线程池能够带来3个好处. 1. 降低资源消耗.通过重复利用已创建的线程降低线程 ...
- java多线程系列六、线程池
一. 线程池简介 1. 线程池的概念: 线程池就是首先创建一些线程,它们的集合称为线程池. 2. 使用线程池的好处 a) 降低资源的消耗.使用线程池不用频繁的创建线程和销毁线程 b) 提高响应速度,任 ...
随机推荐
- Android应用公布后的统计——百度移动统计的应用
一个App公布到各个渠道之后,我们须要採集不同渠道的一些信息,比方app在执行过程中产生的一些异常信息,app在各个android版本号的分布,以及各个app版本号的分布,各渠道的用户数,用户忠诚度等 ...
- ios开发之-计算器的改进
#import <Foundation/Foundation.h> extern double add(double x,double y); extern double subtract ...
- tcp_tw_recycle检查tcp_timestamps的内核代码
注意:本文档中的内核代码的版本号:linux-4.0.5 /************************************************* * Author : Samson * ...
- Eclipse上开发IBM Bluemix应用程序
林炳文Evankaka原创作品. 转载请注明出处http://blog.csdn.net/evankaka 摘要:本文主要解说了怎样使用安装EclipseIBM Bluemix插件.并在Eclipse ...
- EC2 开启 IPV6 访问 和 禁止重启后自动分配IP地址
EC2 开启 IPV6 访问 和 禁止重启后自动分配IP地址进入 VPC 控制台,对当前 VPC 添加 IPV6 CIDR 块对该 VPC 的路由表进行修改,添加其它路由,第一个空填::/0,第二个空 ...
- 误操作 rpm -e --nodeps zlib
误删缘由:目的是要升级ssh版本,结果好像是冥冥之中有股力量在作祟迫使我粘了一条致死的命令rpm -e --nodeps zlib就执行了,奇怪的是执行之后根本就全然不知.最后在敲rpm命令时居然报 ...
- SpringBoot与Dubbo整合-项目搭建
本章节建立生产者和消费者来演示dubbo的demo 生产者:springboot-dubbo-provider 和 消费者:springboot-dubbo-consumer 工程配置详解 Apach ...
- H265(HEVC) nal 单元头介绍及rtp发送中的fu分组发送详解
首先来介绍下h265(HEVC)nal单元头,与h264的nal层相比,h265的nal unit header有两个字节构成,如下图所示: 从图中可以看出hHEVC的nal包结构与h264有明显的不 ...
- C++ 补课 (三)
1,枚举类型 —— 下标自0开始 enum 枚举类型名 { 常数表 } 2,C++ 的异常处理机制实际上是一种运行时通知机制 3,delete p;只是删除指针p指向内存区,并不是删除指针p,所以p还 ...
- jq实现回车键执行方法
$(function(){ $(document).keypress(function (e){ if(e.keyCode == 13){ //执行你想执行的方法,keyCode代表不同的按键 } } ...