線程池是如何清理線程的,當(dāng)大于核心數(shù)量的線程數(shù),或者已經(jīng)超時(shí)了.那么getTask會(huì)返回一個(gè)空(wc > corePoolSize且隊(duì)列為空),此時(shí)runWorker就會(huì)退出死循環(huán).那么這個(gè)線程就會(huì)自動(dòng)被清理掉.
一個(gè)線程只能start一次.線程池復(fù)用線程就是依賴(lài)一個(gè)死循環(huán),不斷的取任務(wù).
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//getTask也是死循環(huán).
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
獲取任務(wù).注意下什么時(shí)候會(huì)返回null.因?yàn)檫@個(gè)null會(huì)導(dǎo)致線程的退出;
1.rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())
線程池狀態(tài)不滿足了
2.(wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())
1.線程數(shù)量大于最大線程數(shù)量或者
2.timed:allowCoreThreadTimeOut || wc > corePoolSize;
3.且timeout.
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 {
//要不要執(zhí)行超時(shí)的take.
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
添加工作者
主要工作:1.compareAndIncrementWorkerCount
2.t.start();
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
//狀態(tài)校驗(yàn).如果狀態(tài)大于等于shutdown接著往下判斷
//如果不等于shutdown直接返回false,如果等于shutdown接著判斷,如果firstTask不等于空,
//直接返回false,如果firstTask不等于null,返回false,如果firstTask等于null,
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
//cas死循環(huán)添加.
for (;;) {
//
int wc = workerCountOf(c);
//線程數(shù)量不能大于等于Capacity.如果不大于CAPACITY,還有一個(gè)corePoolSize或者
//maximumPoolSize的判斷
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
//
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();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
RejectedExecutionHandler
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
拒絕策略是如何執(zhí)行的.先看看任務(wù)是如何執(zhí)行的.
1.線程數(shù)量小于核心線程數(shù),嘗試新增一個(gè)線程.
2.任務(wù)成功入隊(duì)列,雙重檢驗(yàn)是否還需要添加一個(gè)線程.
3.如果無(wú)法入隊(duì)列,那么嘗試添加一個(gè)線程,如果失敗,那么線程池要么被關(guān)閉了,要么就發(fā)生線程飽和的情況,我們就執(zhí)行拒絕策略.
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:作者的總結(jié).
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
//小于corePoolSize
if (workerCountOf(c) < corePoolSize) {
//command成為firstTask.
if (addWorker(command, true))
return;
c = ctl.get();
}
//加入工作隊(duì)列.
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))
reject(command);
線程的拒絕策略:
1.AbortPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
2.CallerRunsPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
3.DiscardOldestPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
4.DiscardPolicy
Does nothing, which has the effect of discarding task r.
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}