对于ThreadPoolExecutor这个线程池,我经过一些简单的测试验证发现,想要看看,是不是corePoolSize初始值的线程数用完就会马上新增线程直到最大线程池maximumPoolSize满为止,最后才往等待队列workQueue里面塞? 然而实际上并非如此。
首先让我们看下ThreadPoolExecutor的通用构造函数:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,TimeUnit unit,
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
RejectedExecutionHandler handler) { ... }
经验证,该函数的相关规则如下:
1)当线程池小于corePoolSize时,新提交任务将创建一个新线程执行任务,即使此时线程池中存在空闲线程。
2)当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行
3)当workQueue已满,且maximumPoolSize>corePoolSize时,新提交任务会创建新线程执行任务
4)当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理
5)当线程池中超过corePoolSize线程,空闲时间达到keepAliveTime时,关闭空闲线程
6)当设置allowCoreThreadTimeOut(true)时,线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭。
可以看出,allowCoreThreadTimeOut这个方法就像其字面的意思一样,允许Core Thread超时后可以关闭。
而allowCoreThreadTimeOut在对应的英文:
In Java 6, allowCoreThreadTimeOut allows you to request that all pool threads be able to time out; enable this feature with a core size of zero if you want a bounded thread pool with a bounded work queue but still have all the threads torn down when there is no work to do.
可以看出,要想使线程池没有任务时销毁所有的进程,需要启用allowCoreThreadTimeOut(true)同时将core size设置为0,而实际上,core size设置成任意一个正整数值就可以,设置成0时,加不加allowCoreThreadTimeOut(true)都没有影响,因为这个方法是对core thread产生影响,但此时core thread为0,而且当新任务进来时,必须等到workQueue满时才会创建新线程,这并非我们需要的结果。