先說結論:它是指大於核心線程數的線程空閒多久後被移除。
首先要明白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。