ThreadPoolExecutor是Executor框架的一个主要实现类,是执行具体任务的实现类。该实现类有Executor中的工厂类Executors提供的静态工厂方法负责创建。主要静态方法看下图:
通过类图可以发现,Executors主要可以创建3种类型的ExecutorService实现类:newFixedThreadPool、newSingleThreadExecutor、newCachedThreadPool。
虽然他们返回的是不同类型的ThreadPoolExecutor,其实底层都是调用ThreadPoolExecutor的构造方法,通过传入不同的构造参数来构造出不同类型的线程池,所以返回的实现类都是ThreadPoolExecutor。
现在可以看下3种不同类型的线程池的具体应用场景
newFixedThreadPool:根据方法名可以看出,是创建了固定 线程数量的线程池,所以返回的ThreadPoolExecutor中的线程池的数量是固定的,可以通过参数进行指定初始化的线程数量,该线程池适用于为了满足资源管理的需求,而需要限制当前线程数量的应用场景。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
newSingleThreadExecutor:该类型的线程池与newFixedThreadPool创建的类型有相似之处,其实都是固定数量的,只不过该线程数量是固定的一个,不能通过参数进行自定义,线程池中始终是单个线程在执行任务。该线程池适用于需要保证顺序的执行各个任务;并且在任意是时间点,不会有多个线程是活动的场景。
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
newCachedThreadPool:该线程池大小没有限制的线程池,其实也不是没有限制,只是限制的值比较大,等于Integer.MAX_VALUE。具体的请看方法源码,该线程池适用于执行很多的短期异步任务的小程序,或者是负载较轻的服务器。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}