上篇博文《线程池源码解析》中,遗留了一个问题,拒绝策略。
这篇文章,大概说一下。
ThreadPoolExecutor
类中,线程池的拒绝策略有四种
- AbortPolicy 默认策略,丢弃任务,直接抛出异常。
- CallerRunsPolicy 由提交任务的线程,来执行任务。
- DiscardPolicy 丢弃任务,不抛异常,实际是啥也不做。
- DiscardOldestPolicy 将队列中老的任务丢弃,然后提交当前任务。
现在看下它们各自的源码
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
// 1、工作线程数量小于核心线程数,创建线程
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
// 2、将任务放入阻塞队列