1、概述
keepAliveTime是多余的线程等待新任务的最长时间,超过这个时间多余的线程将被终止。
2、runWorker
工作线程主要是执行runWorker。如果从工作队列中获取的task为空,则线程终止。
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
3、getTask
当从工作队列中获取新任务超时时,会将标志timeout设置为true。在进入下一次循环中,有以下几种情况会返回任务为null。
- 在工作线程数大于maximumPoolSize并且最大线程数大于1时,在什么情况下会出现这种情况呢?在调用线程池的setMaximumPoolSize时。
- 工作线程数在核心线程数与最大线程数之间,超时标志timeout为true,工作线程数大于1或者工作队列为空
- 设置了允许核心线程超时标志(allowCoreThreadTimeout),超时标志timeout为true,并且工作线程数大于1或者工作队列为空
在满足上面三种情况时,在cas设置工作线程数成功情况下,getTask返回null。