線程池ThreadPoolExecutor工作原理
阿新 • • 發佈:2018-07-19
man ase abs 狀態 導致 isalive thrown rup 不能添加
前言
工作原理
如果使用過線程池,細心的同學肯定會註意到,new一個線程池,但是如果不往裏面提交任何任務的話,main方法執行完之後程序會退出,但是如果向線程池中提交了任務的話,main方法執行完畢之後程序是不會自動退出的,是什麽原理,或者說是什麽原因導致任務提交到線程池之後任務執行完程序無法自動退出的呢?下面就讓我們趴開線程池的源碼,一探究竟。
我們直接從ThreadPoolExecutor的execute方法開始說起。線程提交到ThreadPoolExecutor執行分為三種情況,具體如下:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get(); //1、當前線程池中的線程數小於corePoolSize if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); } //2、當前線程池中的線程數大於corePoolSize,直接將任務放入工作隊列 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); } //3、如果入隊失敗,嘗試啟動新的線程,即此時工作隊列已滿,線程池中的線程數大於corePoolSize小於maxPoolSize else if (!addWorker(command, false)) reject(command);//啟動新的線程失敗,執行拒絕策略 }
現在我們知道,將一個任務提交到ThreadPoolExecutor線程池執行分為三種情況,可以看到,三種情況下都有一個addWorker的動作,下面我們主要看看addWorker裏面做了什麽
private boolean addWorker(Runnable firstTask, boolean core) { // 第一步,cas操作保證正確的增加任務數 retry: for (;;) { int c = ctl.get(); int rs = runStateOf(c); // 如果當前線程池不處於RUNNING狀態,則不能添加任務 if (rs >= SHUTDOWN && // 如果線程池狀態rs >= SHUTDOWN,也就是非RUNNING狀態,此時不接受新任務 ! (rs == SHUTDOWN && //rs == SHUTDOWN ,此狀態不接受新任務 firstTask == null && ! workQueue.isEmpty())) // 工作隊列不為空 return false; for (;;) { // 獲取任務數量 int wc = workerCountOf(c); //如果線程數 大於等於CAPACITY 添加任務失敗 if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize)) return false; if (compareAndIncrementWorkerCount(c))//嘗試增加任務數量 break retry; c = ctl.get(); // Re-read ctl // 如果當前的運行狀態不等於rs,說明狀態已被改變,返回第一個for循環繼續執行 if (runStateOf(c) != rs) continue retry; // else CAS failed due to workerCount change; retry inner loop } } // 第二步 創建一個Worker,包裝當前的任務,並啟動該work中創建的線程,用於執行當前當前提交過來的任務 boolean workerStarted = false; boolean workerAdded = false; Worker w = null; try { w = new Worker(firstTask);//新建一個worker,同時從ThreadFactory中創建一個新的線程 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);//放入worker集合 int s = workers.size(); if (s > largestPoolSize) largestPoolSize = s; workerAdded = true; } } finally { mainLock.unlock(); } if (workerAdded) {//worker添加成功,啟動任務 t.start(); workerStarted = true; } } } finally { if (! workerStarted) addWorkerFailed(w); } return workerStarted; }
這裏分為兩步,首先使用cas操作保證成功增加workerCount,然後將創建一個worker,將worker添加人worker池,啟動worker,返回任務添加成功
Worker是ThreadPoolExecutor線程池的內部類,主要作為用戶提交任務的包裝,它繼承自AbstractQueuedSynchronizer類並實現了Runnable接口,它的run方法很簡單,直接調用runWorker方法,runWorker如下:
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) {
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);
}
}
可以看到,在runWorker中使用了一個while循環,使用getTask去獲取任務, getTask如下:
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 {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
getTask通過workQueue.take();方法獲取任務,我們知道,blockingQueue的take方法是阻塞的,當隊列為空時,會一直阻塞知道獲取新的任務,到這裏,我們便可以回答上面提到的問題了
重新梳理一遍,用戶向ThreadPoolExecutor線程池中添加任務時,ThreadPoolExecutor會創建一個Worker,用來包裝並執行用戶任務,Worker的run方法中采用while循環,通過getTask方法不斷的取出工作隊列中的任務執行,當任務隊列為空時,take方法阻塞了線程,導致任務執行線程一直不會退出,所以用戶想ThreadPoolExecutor線程池中提交任務之後程序不會自動結束,就是這個原理。
線程池ThreadPoolExecutor工作原理