ThreadPoolExecutor有三个参数是用来管理内部池的大小,分别是corePoolSize,maximumPoolSize,workQueue
从源码可以看出,池控制的策略如下:
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.