在线程池中,核心线程相当于长期员工,需要一直存在,而线程数大于核心线程数时,必然会出现临时工,在空闲时被清除以防浪费线程资源,剩下的线程即作为新的核心线程继续工作
线程池相关代码如下:
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
// Check if queue empty only if necessary.
if (runStateAtLeast(c, SHUTDOWN)
&& (runStateAtLeast(c, 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;
}
}
}
关键变量及方法分析:
timedOut:线程空闲时间是否已经超时
allowCoreThreadTimeOut:是否允许核心线程超时被回收,一般而言核心线程是允许超时等待新任务执行的,默认视为false;需要回收核心线程时自定义为true,此时timed也会一直为true
timed:是否有worker(即线程池中的线程)需要被“裁员”,当线程数量超过核心线程数时为ture,
否则取决于allowCoreThreadTimeOut
compareAndDecrementWorkerCount():通过CAS竞争“下岗”资格,使线程数量-1
c:线程池状态
wc:线程的数量
流程1:
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
// Check if queue empty only if necessary.
if (runStateAtLeast(c, SHUTDOWN)
&& (runStateAtLeast(c, STOP) || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
当getTask()方法被调用时,每个线程都会进入一个死循环,并在进入循环前将timedOut设置为false(因为此时线程默认都是没有超时的)