ThreadPoolExecutor提交任務(wù)入口代碼如下:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
// ctl高3位表示線程池狀態(tài)拣技,低29位表示線程數(shù)目拴签,對(duì)ctl的訪問需要進(jìn)行位運(yùn)算
int c = ctl.get();
// 如果worker線程數(shù)目小于corePoolSize娃弓,增加一個(gè)worker線程
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
// 如果worker線程不小于corePoolSize凸舵,并且線程池正在運(yùn)行贮竟,則把任務(wù)添加到workQueue中
// workQueue是一個(gè)BlockingQueue<Runnable>
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
// 再次獲取線程池狀態(tài)碼并檢測(cè)線程池是否運(yùn)行,如果沒有運(yùn)行掷倔,則移除剛才提交的任務(wù)眉孩,調(diào)用reject方法
// reject方法可以由RejectedExecutionHandler指定
if (! isRunning(recheck) && remove(command))
reject(command);
// 如果worker線程數(shù)目為0,以maximumPoolSize為限制增加一個(gè)worker線程
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// 如果任務(wù)添加到workQueue(有可能是有界隊(duì)列)失敗勒葱,
// 以maximumPoolSize為限制增加一個(gè)worker線程
// 如果增加線程失敗勺像,調(diào)用reject方法
else if (!addWorker(command, false))
reject(command);
}
看完任務(wù)如何提交障贸,繼續(xù)看addWorker方法是怎么運(yùn)行的,只留下了方法的主干:
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// 檢測(cè)條件
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
// 如果worker線程數(shù)目大于CAPACITY(ctl的低29位全為1吟宦,500多萬)
// 或者worker線程大于corePoolSize,maximumPoolSize(用core開關(guān)控制)
// 添加worker線程失敗
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
// CAS操作涩维,增加worker線程數(shù)目
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
}
}
// 增加worker線程測(cè)試條件通過殃姓,真正開始增加worker線程
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
// new一個(gè)Worker,Worker是對(duì)線程和任務(wù)的一個(gè)封裝瓦阐,下面會(huì)講到
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// 在workers里面新增worker
workers.add(w);
int s = workers.size();
// 更新largestPoolSize
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
// 如果worker添加成功蜗侈,則啟動(dòng)這個(gè)worker線程
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
// 如果啟動(dòng)worker失敗,調(diào)用addWorkerFailed方法
// 這個(gè)方法主要是減少worker數(shù)目睡蟋,從workers里面移除剛才添加的worker
// 并在線程池中嘗試中斷一個(gè)idle worker
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
下面接著看Worker是怎么對(duì)線程與任務(wù)封裝的踏幻,下面是Worker類的代碼:
// Worker類本身也是一個(gè)Runnable
// AQS可以這樣理解,它內(nèi)部持有一個(gè)狀態(tài)戳杀,并發(fā)的線程可以原子性的去修改這個(gè)狀態(tài)
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
// 運(yùn)行任務(wù)的線程
final Thread thread;
// 初始化運(yùn)行的任務(wù)该面,可以為null
Runnable firstTask;
// 完成任務(wù)的計(jì)數(shù)
volatile long completedTasks;
Worker(Runnable firstTask) {
setState(-1); // 狀態(tài)設(shè)置為-1,禁止沒有start線程前去中斷這個(gè)線程
this.firstTask = firstTask;
// 傳的是this對(duì)象信卡,所以線程start會(huì)調(diào)用this的run方法
this.thread = getThreadFactory().newThread(this);
}
// run方法委托給runWorker方法隔缀,參數(shù)傳的是this
public void run() {
runWorker(this);
}
// 關(guān)于鎖的方法
// 通過lock與unlock,可以知道worker是不是idle worker
// 0代表沒有加鎖狀態(tài)
// 1代表加鎖狀態(tài)
protected boolean isHeldExclusively() {
return getState() != 0;
}
protected boolean tryAcquire(int unused) {
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
protected boolean tryRelease(int unused) {
setExclusiveOwnerThread(null);
setState(0);
return true;
}
public void lock() { acquire(1); }
public boolean tryLock() { return tryAcquire(1); }
public void unlock() { release(1); }
public boolean isLocked() { return isHeldExclusively(); }
// 線程運(yùn)行后也可以通過這個(gè)方法中斷線程的運(yùn)行
void interruptIfStarted() {
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}
}
下面來看看runWorker方法傍菇,只留下了方法的主干:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread(); //獲取到worker的thread
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // unlock worker猾瘸,允許中斷thread
boolean completedAbruptly = true;
// 死循環(huán),當(dāng)task為null或者從任務(wù)隊(duì)列獲取任務(wù)為null時(shí)丢习,worker的thread會(huì)退出
while (task != null || (task = getTask()) != null) {
w.lock(); // lock表示這個(gè)worker不是idle worker
// 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 {
Throwable thrown = null;
try {
// 運(yùn)行任務(wù)
task.run();
} catch (Throwable x) {
thrown = x;
throw new Error(x);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
}
下面接著看worker線程是如何從任務(wù)隊(duì)列獲取任務(wù)的:
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// 如果線程池狀態(tài)至少為shutdown牵触,并且
// 線程池狀態(tài)至少為stop或者工作隊(duì)列為空
// 減少worker的數(shù)目,并返回null咐低,當(dāng)worker線程檢測(cè)到任務(wù)為null時(shí)揽思,會(huì)自己退出
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// 當(dāng)allowCoreThreadTimeOut為true或者worker線程數(shù)目大于corePoolSize時(shí),允許超時(shí)
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
// 如果worker線程數(shù)目大于maximumPoolSize渊鞋,或者
// 允許超時(shí)并且上一次poll也超時(shí)绰更,并且
// worker線程數(shù)目大于1,或者工作隊(duì)列為空
// 減少worker線程數(shù)目返回null
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
// 允許超時(shí)則用poll锡宋,否則take
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
以上就是整個(gè)ThreadPoolExecutor主要的方法儡湾,還有另一個(gè)比較重要的方法,是用來清除idle worker的:
private void interruptIdleWorkers(boolean onlyOne) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (Worker w : workers) {
Thread t = w.thread;
// 如果worker的thread沒有中斷执俩,并且嘗試去獲取worker的鎖
// 成功則表示worker沒有運(yùn)行任務(wù)徐钠,那么中斷這個(gè)idle worker
// 失敗則表示worker正在運(yùn)行任務(wù),不中斷這個(gè)worker
if (!t.isInterrupted() && w.tryLock()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
} finally {
w.unlock();
}
}
if (onlyOne)
break;
}
} finally {
mainLock.unlock();
}
}