Android線程池源碼閱讀記錄介紹
今天面試被問到線程池如何復用線程的?當場就懵掉了...于是面試完畢就趕緊打開源碼看了看,在此記錄下:
我們都知道線程池的用法,一般就是先new一個ThreadPoolExecutor對象,再調用execute(Runnable runnable)傳入我們的Runnable,剩下的交給線程池處理就行了,于是這次我就從ThreadPoolExecutor的execute方法看起:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 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();
//1.如果workerCountOf(c)即正在運行的線程數(shù)小于核心線程數(shù),就執(zhí)行addWork
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
//2.如果線程池還在運行狀態(tài)并且把任務添加到任務隊列成功
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
//3.如果線程池不在運行狀態(tài)并且從任務隊列移除任務成功,執(zhí)行線程池飽和策略(默認直接拋出異常)
if (! isRunning(recheck) && remove(command))
reject(command);
//4.否則如果此時運行線程數(shù)==0,就直接調用addWork方法
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
//5.如果2條件不成立,繼續(xù)判斷如果addWork返回false,執(zhí)行線程池飽和策略
else if (!addWorker(command, false))
reject(command);
}
大致過程就是如果核心線程未滿,則直接addWorker(該方法下面會再分析);如果核心線程已滿,則嘗試將任務加進消息隊列中,并再判斷如果此時運行線程數(shù)==0則調addWorker方法,否則不做任何處理(因為運行的線程處理完自己的任務后會去消息隊列中取任務來執(zhí)行,下面會分析);如果任務隊列添加任務失敗,那么直接addWorker(),如果addWorker返回false,執(zhí)行飽和策略,下面我們就來看看addWorker里面做了什么
/**
* @param firstTask the task the new thread should run first (or
* null if none). Workers are created with an initial first task
* (in method execute()) to bypass queuing when there are fewer
* than corePoolSize threads (in which case we always start one),
* or when the queue is full (in which case we must bypass queue).
* Initially idle threads are usually created via
* prestartCoreThread or to replace other dying workers.
*
* @param core if true use corePoolSize as bound, else
* maximumPoolSize. (A boolean indicator is used here rather than a
* value to ensure reads of fresh values after checking other pool
* state).
* @return true if successful
*/
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 (;;) {
int wc = workerCountOf(c);
//1.如果正在運行的線程數(shù)大于corePoolSize 或 maximumPoolSize(core代表以核心線程數(shù)還是最大線程數(shù)為邊界),return false,表示addWorker失敗
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
//2.否則將運行線程數(shù)+1,并跳出這個for循環(huán)
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 {
//3.創(chuàng)建一個Worker對象,傳入我們的runnable
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) {
//4.開始啟動線程
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker. */
public void 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 {
//1.當firstTask不為空或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 {
//2.執(zhí)行任務
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);
}
}
可以看到addWorker方法主要就是先判斷正在運行線程數(shù)是否超過了最大線程數(shù)(具體根據(jù)邊界?。?,如果未超過則創(chuàng)建一個worker對象,其中firstTask是我們傳入的Runnable,當然根據(jù)上面的execute方法可知當4條件滿足時,傳入的firstTask是null,Thread是用ThreadFactory創(chuàng)建的線程,傳入的Runnable是Worker自己,最后開啟線程,于是執(zhí)行Worker這里的run、runWorker方法,在runWorker方法里,開啟一個while循環(huán),當firstTask不為空或getTask不為空時,執(zhí)行task,下面我們接著看看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?
//1.會不會淘汰空閑線程
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
//2.return null意味著回收一個Worker即淘汰一個線程
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
//3.等待指定時間
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
可以看1、2注釋,allowCoreThreadTimeOut代表存活一定時間是否對核心線程有效(默認為false),先看它為ture的情況,此時不管是核心線程還是非核心線程在3處都會等待一定時間(就是我們傳入的線程?;顣r間),等待時間內如果從任務隊列取到任務,則返回執(zhí)行,否則timeout為true,繼續(xù)走到2,由于(timed && timedOut)和workQueue.isEmpty()均為true,返回null,代表回收一個線程;如果allowCoreThreadTimeOut為false,代表不回收核心線程,此時如果在3處沒有取到任務,繼續(xù)執(zhí)行到2處,只有當wc > corePoolSize或wc > maximumPoolSize時才會執(zhí)行return null,否則一直循環(huán),相當于該線程一直處于運行狀態(tài),直到從任務隊列拿到新的任務
到此這篇關于Android線程池源碼閱讀記錄介紹的文章就介紹到這了,更多相關Android線程池內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解Android獲取系統(tǒng)內核版本的方法與實現(xiàn)代碼
這篇文章主要介紹了詳解Android獲取系統(tǒng)內核版本的方法與實現(xiàn)代碼的相關資料,這里提供了具體實現(xiàn)獲取內核的方法,需要的朋友可以參考下2017-07-07
Android Studio中生成aar文件及本地方式使用aar文件的方法
這篇文章給大家講解Android Studio中生成aar文件以及本地方式使用aar文件的方法,也就是說 *.jar 與 *.aar 的生成與*.aar導入項目方法,本文給大家介紹的非常詳細,需要的朋友參考下吧2017-12-12
Android 封裝Okhttp+Retrofit+RxJava,外加攔截器實例
下面小編就為大家分享一篇Android封裝Okhttp+Retrofit+RxJava,外加攔截器實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01
解決Android啟動APP的一瞬間系統(tǒng)欄會變成藍色問題
這篇文章主要介紹了解決Android啟動APP的一瞬間系統(tǒng)欄會變成藍色問題,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06
android開發(fā)之為activity增加左右手勢識別示例
這篇文章主要介紹了android開發(fā)中為activity增加左右手勢識別示例,需要的朋友可以參考下2014-04-04
Android UI設計與開發(fā)之實現(xiàn)應用程序只啟動一次引導界面
這篇文章主要為大家詳細介紹了Android UI設計與開發(fā)之實現(xiàn)應用程序只啟動一次引導界面,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08

