The meaning of parameters in java ThreadPoolExecutor
corePoolSize: the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize: the maximum number of threads to allow in the pool keepAliveTime when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
unit : the time unit for the keepAliveTime argument
workQueue: the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
handler: the handler to use when execution is blocked because the thread bounds and queue capacities are reache
- corePoolSize(核心线程数)
线程池中会始终保持的最小线程数
即使这些线程处于空闲状态,也不会被销毁(除非设置了allowCoreThreadTimeOut为true)
这些线程响应速度最快,因为不需要创建新线程
- maximumPoolSize(最大线程数)
线程池允许创建的最大线程数
当工作队列满了,且当前线程数小于maximumPoolSize时,会创建新线程
超过这个数量的任务会触发拒绝策略
- keepAliveTime(空闲线程存活时间)
非核心线程空闲超过这个时间后会被销毁
如果allowCoreThreadTimeOut为true,核心线程也会受这个参数影响
用于减少资源浪费
- unit(时间单位)
keepAliveTime的时间单位
可以是SECONDS、MINUTES等TimeUnit枚举值
- workQueue(工作队列)
用于存放待执行的任务
常用队列类型:
ArrayBlockingQueue:有界队列
LinkedBlockingQueue:无界队列
SynchronousQueue:无缓冲的等待队列
PriorityBlockingQueue:优先级队列
- handler(拒绝策略)
当队列满且线程数达到maximumPoolSize时的处理策略
默认策略类型:
AbortPolicy:抛出异常(默认)
CallerRunsPolicy:在调用者线程执行
DiscardPolicy:直接丢弃
DiscardOldestPolicy:丢弃最早的任务
planUML描述如下:
1 | @startuml |