public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }
在ThreadPoolExecutor方法的參數(shù)注釋中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.
就是線程數(shù)大于corePoolSize時空閑線程存活的最大時間。在方法getTask中就可明白具體是怎么實現(xiàn)的羡儿。
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
注意到工作線程數(shù)wc大于corePoolSize或allowCoreThreadTimeOut為true時timed為true授霸。
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
poll方法超時后timeOut變?yōu)閠rue劲弦。
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
在下一次循環(huán)中下面判斷條件為真,執(zhí)行了compareAndDecrementWorkerCount方法,當前線程跳出循環(huán)。
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
getTask返會null后柿估,執(zhí)行了processWorkerExit方法歧譬,當前Worker被移除岸浑。
workers.remove(w);