ThreadPoolExecutor的corePoolSize、maximumPoolSize和poolSize
看两段源码:
以上可以看出,ThreadPoolExecutor的主要参数有:corePoolSize , maximumPoolSize , keepAliveTime ,workQueue,threadFactory,handler ,对于几个参数,我们该如何理解呢? 先看看这几个参数: corePoolSize : 顾名思义,核心线程大小,即在没有任务需要执行的时候线程池的大小,并且只有在工作队列满了的情况下才会创建超出这个数量的线程; maximuxPoolSize : 线程池中允许创建的最大线程数大小; poolSize : 当前线程池中线程的数量,当改值为0的时候,意味着没有任何线程,线程池会终止;同时,poolSize不会超过maximumPoolSize; 看看官方解释: Queuing Any BlockingQueue may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing: ● 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. 理解: 1、如果当前线程池的线程数还没有达到核心线程数大小,即 poolSize < corePoolSize ,无论是否有空闲的线程,系统回新增一个线程来处理新提交的任务; 2、如果当前线程池的线程数大于或者等于核心线程数大小,即 poolSize >= corePoolSize,且任务队列未满时,将提交的任务提交到阻塞队列中,等待处理workQueue.offer(command); 3、如果当前线程池的线程数大于或者等于核心线程数大小,即 poolSize >= corePoolSize,且任务队列已满时,分以下两种情况: 3.1、poolSize < maximumPoolSize ,新增线程来处理任务; 3.2、poolSize = maximuxPoolSize ,意味中线程池的处理能力已经达到极限,此时会拒绝增加新的任务,至于如何拒绝,取决于RejectedExecutionHandler
|