ThreadPoolExecutor的线程池控制策略

ThreadPoolExecutor有三个参数是用来管理内部池的大小,分别是corePoolSize,maximumPoolSize,workQueue

public void execute(Runnable command) { if (command == null) throw new NullPointerException(); for (;;) { if (runState != RUNNING) { reject(command); return; } if (poolSize < corePoolSize && addIfUnderCorePoolSize(command)) return; if (workQueue.offer(command)) return; Runnable r = addIfUnderMaximumPoolSize(command); if (r == command) return; if (r == null) { reject(command); return; } // else retry } }

从源码可以看出,池控制的策略如下:

1. 如果当前池容量小于corePoolSize时,启动新的线程去执行command任务

2. 当前池容量大于corePoolSize,但是小于maximumPoolSize时,将任务加入到workQueue中,直至队列满;这种情况下,任务会由线程池中的空闲线程取出执行

3. 当线程队列workQueue也满了的情况下,若池容量尚未达到maximumPoolSize时,则将处于workQueue的队列头的任务取出,并启动新的线程来执行;此时应用要求执行的command任务既没有放入队列,也没有在线程中执行,而是再次进入这个池控制流程,直至该command任务被处理

下面是JAVA API中对线程队列的一段描述:

  • If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.
  • If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.
  • If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值