Java线程池类ThreadPoolExecutor的使用 JDK自带的4种线程池
程序员文章站
2022-07-12 19:51:00
...
首先,继承关系: Executor -> ExecutorService -> AbstractExecutorService -> ThreadPoolExecutor Interface: Executor.execute(Runnable) Interface: ExecutorService.submit(Callable) -- ExecutorService implements Executor AbstractExecutorService实现了submit(Callable),这个需要调用execute(Runnable)来实现, 正是AbstractExecutorService的子类ThreadPoolExecutor中实现了execute(Runnable) 参数最全的构造方法 * @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @param maximumPoolSize the maximum number of threads to allow in the * pool * @param keepAliveTime when the number of threads is greater than * the core, this is the maximum time that excess idle threads * will wait for new tasks before terminating. * @param unit the time unit for the {@code keepAliveTime} argument * @param workQueue the queue to use for holding tasks before they are * executed. This queue will hold only the {@code Runnable} * tasks submitted by the {@code execute} method. * @param threadFactory the factory to use when the executor * creates a new thread * @param handler the handler to use when execution is blocked * because the thread bounds and queue capacities are reached public ThreadPoolExecutor( int corePoolSize, // int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) JDK自带的配置好的线程池: // 固定工作线程数量的线程池 ExecutorService executorService1 = Executors.newFixedThreadPool(3); // 一个可缓存的线程池 ExecutorService executorService2 = Executors.newCachedThreadPool(); // 单线程化的Executor ExecutorService executorService3 = Executors.newSingleThreadExecutor(); // 支持定时的以及周期性的任务执行 ExecutorService executorService4 = Executors.newScheduledThreadPool(3); 1.CachedThreadPool CachedThreadPool首先会按照需要创建足够多的线程来执行任务(Task)。随着程序执行的过程,有的线程执行完了任务,可以被重新循环使用时,才不再创建新的线程来执行任务。我们采用《Thinking In Java》中的例子来分析。 首先,任务定义如下(实现了Runnable接口,并且复写了run方法): package net.jerryblog.concurrent; public class LiftOff implements Runnable{ protected int countDown = 10; //Default private static int taskCount = 0; private final int id = taskCount++; public LiftOff() {} public LiftOff(int countDown) { this.countDown = countDown; } public String status() { return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff!") + ") "; } @Override public void run() { while(countDown-- > 0) { System.out.print(status()); Thread.yield(); } } } 采用CachedThreadPool方式执行编写的客户端程序如下: package net.jerryblog.concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CachedThreadPool { public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); for(int i = 0; i < 10; i++) { exec.execute(new LiftOff()); } exec.shutdown(); } } 上面的程序中,有10个任务,采用CachedThreadPool模式,exec没遇到一个LiftOff的对象(Task),就会创建一个线程来处理任务。现在假设遇到到第4个任务时,之前用于处理第一个任务的线程已经执行完成任务了,那么不会创建新的线程来处理任务,而是使用之前处理第一个任务的线程来处理这第4个任务。接着如果遇到第5个任务时,前面那些任务都还没有执行完,那么就会又新创建线程来执行第5个任务。否则,使用之前执行完任务的线程来处理新的任务。 2.FixedThreadPool FixedThreadPool模式会使用一个优先固定数目的线程来处理若干数目的任务。规定数目的线程处理所有任务,一旦有线程处理完了任务就会被用来处理新的任务(如果有的话)。这种模式与上面的CachedThreadPool是不同的,CachedThreadPool模式下处理一定数量的任务的线程数目是不确定的。而FixedThreadPool模式下最多的线程数目是一定的。 采用FixedThreadPool模式编写客户端程序如下: package net.jerryblog.concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FixedThreadPool { public static void main(String[] args) { //三个线程来执行五个任务 ExecutorService exec = Executors.newFixedThreadPool(3); for(int i = 0; i < 5; i++) { exec.execute(new LiftOff()); } exec.shutdown(); } } 3.SingleThreadExecutor模式 SingleThreadExecutor模式只会创建一个线程。它和FixedThreadPool比较类似,不过线程数是一个。如果多个任务被提交给SingleThreadExecutor的话,那么这些任务会被保存在一个队列中,并且会按照任务提交的顺序,一个先执行完成再执行另外一个线程。 SingleThreadExecutor模式可以保证只有一个任务会被执行。这种特点可以被用来处理共享资源的问题而不需要考虑同步的问题。 SingleThreadExecutor模式编写的客户端程序如下: package net.jerryblog.concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SingleThreadExecutor { public static void main(String[] args) { ExecutorService exec = Executors.newSingleThreadExecutor(); for (int i = 0; i < 2; i++) { exec.execute(new LiftOff()); } } }