ThreadPoolExecutor分析
ThreadPoolExecutor 构建
构造函数
// 带有默认拒绝策略的构造函数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
// 完整的构造函数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {}
参数描述
- corePoolSize 线程池中的线程数量, 最少数量
- maximumPoolSize 最大线程数量
- keepAliveTime 线程最大的等待时间
- unit 上面时间的单位
- workQueue 使用的缓冲队列
- threadFactory 线程队列
- handler 线程满了, 拒绝处理方案
参数5. 缓冲队列说明
线程队列 实现 BlockingQueue, 分为三大类
1: SynchronousQueue (直接移交)同步队列, 只有一个元素, 删除一个, 才能继续添加
2: LinkedBlockingQueue (无线队列)链表队列, 先进先出. 多线程预测性比较差
3: ArrayBlockingQueue (有界队列)数组队列, 先进先出, 大小创建之后无法改变.
参数7. 拒绝策略
实现 接口: RejectedExecutionHandler
- AbortPolicy : 抛出异常
/**
* A handler for rejected tasks that throws a
* {@code RejectedExecutionException}.
*/
- DiscardPolicy : 丢弃拒绝任务
/**
* A handler for rejected tasks that silently discards the
* rejected task.
*/
- DiscardOldestPolicy : 丢弃最老的(队列最先进来的)未处理程序
/**
* A handler for rejected tasks that discards the oldest unhandled
* request and then retries {@code execute}, unless the executor
* is shut down, in which case the task is discarded.
*/
- CallerRunsPolicy : 直接执行被拒绝的 Runnable方法, 在main(主线程)
/**
* A handler for rejected tasks that runs the rejected task
* directly in the calling thread of the {@code execute} method,
* unless the executor has been shut down, in which case the task
* is discarded.
*/