前言
在多線程開發(fā)中,應(yīng)該避免顯式創(chuàng)建線程,而是采用線程池里面的線程谭企。使用線程池可以減少手動(dòng)創(chuàng)建線程,減少線程創(chuàng)建和回收的損耗等评肆。那么使用線程池就需要了解它的原理债查。這里我們ThreadPoolExecutor.execute()方法內(nèi)部的具體實(shí)現(xiàn)邏輯
流程圖
image.png
源碼分析
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
// 獲取狀態(tài)變量
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
// 如果worker個(gè)數(shù)小于核心線程數(shù)量
if (addWorker(command, true))
return;
c = ctl.get();
}
// 嘗試將任務(wù)丟入工作隊(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);
}
// 工作隊(duì)列滿了的話再次嘗試增加worker
else if (!addWorker(command, false))
reject(command);
}
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
// 獲取worker數(shù)量
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
// 判斷是否大于核心線程數(shù)量或者超過線程池總大小
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 {
// 創(chuàng)建新的worker
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// 單線程處理工作者入隊(duì)
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // 這時(shí)候的worker不能已經(jīng)是在運(yùn)行中的
throw new IllegalThreadStateException();
// 將worker加入到工作者的集合中
workers.add(w);
int s = workers.size();
// 更新線程池的當(dāng)前最大size
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
// 如果加入到工作者集合中成功,那么就啟動(dòng)工作者
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
// 這個(gè)方法是工作者的實(shí)際工作內(nèi)容瓜挽,看下工作者是怎么處理任務(wù)的
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // 允許中斷
boolean completedAbruptly = true;
try {
// 如果工作者攜帶的任務(wù)或任務(wù)隊(duì)列不是空的盹廷,就會(huì)一直循環(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 {
// 處理任務(wù)執(zhí)行之后的邏輯
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
// 處理worker退出的邏輯
processWorkerExit(w, completedAbruptly);
}
}