final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
if (w != null)
workers.remove(w);
decrementWorkerCount();
tryTerminate();
} finally {
mainLock.unlock();
}
}
这是添加worker失败的方法
用mainLock锁住
判断如果参数传进来的worker不为空 workers中删除参数worker
然后减少worker数目 然后调用tryTerminate方法关闭空闲的worker
最后mainLock解锁
private void processWorkerExit(Worker w, boolean completedAbruptly) {
if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
decrementWorkerCount();
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
completedTaskCount += w.completedTasks;
workers.remove(w);
} finally {
mainLock.unlock();
}
tryTerminate();
int c = ctl.get();
if (runStateLessThan(c, STOP)) {
if (!completedAbruptly) {
int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
if (min == 0 && ! workQueue.isEmpty())
min = 1;
if (workerCountOf(c) >= min)
return; // replacement not needed
}
addWorker(null, false);
}
}
这个是处理快消亡的worker的方法 传入一个worker和一个布尔值参数代表是否可以突然中止worker
如果布尔参数为true 直接减少worker数目
用mainLock锁定
将线程池的已完成任务数加上参数worker的完成任务数
workers中删除参数worker
mainLock解锁
调用tryTerminate方法关闭空闲worker
获取ctl 判断状态小于STOP
判断如果completedAbruptly为false 创建临时变量min 判断如果allowCoreThreadTimeOut为true min为0 也就是允许核心线程超时 否则min为corePoolSize
如果min为0 且worker队列不为空 min设为1
如果worker数目大于等于min 直接返回 min其实就是线程最小数目
跳出completedAbruptly判断后 添加一个空的worker 就是别让线程池空着