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);
// 削减条件
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;
}
}
}
结论:
1.workerCount不可能一直maxSize
2.线程池中的可用线程大于1时候,只有满足削减条件(削减条件:workerCount > coreSize或者允许核心线程超时),并且超时了,才会削减线程个数
3.线程池中的可用线程为1,只有满足削减条件(削减条件:workerCount > coreSize或者允许核心线程超时),而且队列为空,才会减少线程个数为0