先说结论:它是指大于核心线程数的线程空闲多久后被移除。
首先要明白ThreadPoolExecutor中的Worker是干嘛的?
它其实是一个持有Task工作任务的线程封装类,也就是它来直接执行你提交的task任务的run()的。
从execute方法开始
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))//这里就是大于核心线程数且阻塞队列满了,尝试直接执行task的地方,这个方法很多地方会调用很明显是个核心方法。
reject(command);
}
进入addWorker()
private boolean addWorker(Runnable firstTask, boolean core) {
//。。。这里部分代码省略,主要是线程数和状态的校验,主要看下面的方法
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();-------------启动线程Worker持有的线程。让我们走进run()方法
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
public void run() {
runWorker(this);----------run()方法执行runWorker(this)让我们继续向下看。
}
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) {//getTask()方法是个阻塞方法,也就是keepAliveTime生效的地方。如果超出这个时间没获取到任务则继续向下执行processWorkerExit。
//这里其实就是个循环方法,它会不断尝试获取任务来执行,也就保持线程重复利用。
//省略其他代码
task.run();
//省略其他代码
}
} finally {
processWorkerExit(w, completedAbruptly);
}
}
继续看getTask()
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
//这里依然省略部分代码,主要是些状态和线程数的校验。
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
//当线程数大于核心线程数且获取任务超时,会将WorkerCount减一,并返回为null。然后在调用方移除Worker集合。
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
//这个地方就是利用阻塞队列的超时时间,返回为null来完成的。
//超过keepAliveTime还没有获取到taask,则timedOut设置为true.
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
总结下worker会通过while循环一直getTask()来执行任务,如果getTask()中阻塞队列没有在指定时间返回可执行的任务,则移除当前work。