javathreadpoolexecutor实例_Java线程池(ThreadPoolEx。
。。
Java线程池管理⼯作线程池,它包含⼀个队列,⽤于保持任务等待执⾏。我们可以使⽤ThreadPoolExecutor在Java中创建线程池。
Java线程池管理Runnable线程的集合。⼯作线程从队列中执⾏Runnable线程。urrent.Executors为
urrent.Executor接⼝提供⼯⼚和⽀持⽅法,以在java中创建线程池。
Executors是⼀个实⽤程序类,它还提供了通过各种⼯⼚⽅法使⽤ExecutorService,ScheduledExecutorService,ThreadFactory和Callable类的有⽤⽅法。
下⾯编写⼀个简单的程序来解释它的⼯作原理。
⾸先,我们需要⼀个名为WorkerThread.java并实现Runnable接⼝的类。如下所⽰ -
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s){
thismand=s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
processCommand();
System.out.println(Thread.currentThread().getName()+" End.");
}java线程池创建的四种
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString(){
return thismand;
}
}
ExecutorService⽰例
这是测试程序类 - SimpleThreadPool.java,从Executors框架创建固定线程池。
import urrent.ExecutorService;
import urrent.Executors;
public class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService executor = wFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
在上⾯的程序中,创建⼀个由5个⼯作线程组成的固定⼤⼩的线程池。然后向这个池提交10个作业,因为池⼤⼩为5,它将开始处理5个作业,其他作业将处于等待状态,当其中⼀个作业完成,等待队列中的另⼀个作业将提到给⼯作线程接收并执⾏。
这是上述程序的输出结果 -
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
输出确认池中有五个线程,从“pool-1-thread-1”到“pool-1-thread-5”,它们负责将提交的任务执⾏到池中。
ThreadPoolExecutor⽰例
Executors类使⽤ThreadPoolExecutor提供ExecutorService的简单实现,但ThreadPoolExecutor提供了更多功能。可以指定在创建ThreadPoolExecutor实例时将处于活动状态的线程数,并且可以限制线程池的⼤⼩并创建⾃⼰的RejectedExecutionHandler实现来处理不适合⼯作队列的作业。
下⾯是对RejectedExecutionHandler接⼝的⾃定义实现的⽰例代码 -
import urrent.RejectedExecutionHandler;
import urrent.ThreadPoolExecutor;
public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.String() + " is rejected");
}
}
ThreadPoolExecutor提供了⼏种⽅法,可以使⽤它们出执⾏程序的当前状态,池⼤⼩,活动线程数和任务计数。所以需要有⼀个监视器线程,它将以特定的时间间隔打印执⾏程序信息。
import urrent.ThreadPoolExecutor;
public class MyMonitorThread implements Runnable
{
private ThreadPoolExecutor executor;
private int seconds;
private boolean run=true;
public MyMonitorThread(ThreadPoolExecutor executor, int delay)
{
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", PoolSize(),
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
下⾯是使⽤ThreadPoolExecutor的线程池实现⽰例。
import urrent.ArrayBlockingQueue;
import urrent.Executors;
import urrent.ThreadFactory;
import urrent.ThreadPoolExecutor;
import urrent.TimeUnit;
public class WorkerPool {
public static void main(String args[]) throws InterruptedException{
//RejectedExecutionHandler implementation
RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
//Get the ThreadFactory implementation to use
ThreadFactory threadFactory = Executors.defaultThreadFactory();
//creating the ThreadPoolExecutor
ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue(2), threadFactory, rejectionHandler);
//start the monitoring thread
MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);
Thread monitorThread = new Thread(monitor);
monitorThread.start();
//submit work to the thread pool
for(int i=0; i<10; i++){
}
Thread.sleep(30000);
//shut down the pool
executorPool.shutdown();
//shut down the monitor thread
Thread.sleep(5000);
monitor.shutdown();
}
}
请注意,在初始化ThreadPoolExecutor时,初始池⼤⼩为2,最⼤池⼤⼩为4,⼯作队列⼤⼩为2。因
此,如果有4个正在运⾏的任务并且提交了更多任务,则⼯作队列将只保留其中的2个,其余的将由RejectedExecutionHandlerImpl处理。
以下是上述程序的输出,验证了上述说法。
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.

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。