关于ThreadPoolExecutor线程池的常用参数解读以及实际验证

4 篇文章 0 订阅
4 篇文章 0 订阅

对于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满时才会创建新线程,这并非我们需要的结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值