一、概述
剛開始接觸HandlerThread
是在看AsyncQueryHandler
源碼的時(shí)候,第一次眼看到HandlerThread
這個(gè)名字,就在想這到底是個(gè)Handler
還是個(gè)Thread
,后來看了源碼才發(fā)現(xiàn)它其實(shí)就是一個(gè)Thread
,只不過可以通過它的getLooper
返回的Looper
作為Handler
構(gòu)造函數(shù)的參數(shù),那么這個(gè)新建Handler
所有message
的執(zhí)行都是在這個(gè)對(duì)應(yīng)的Thread
當(dāng)中的,關(guān)于在項(xiàng)目當(dāng)中如何用好HandlerThread
,AsyncQueryHandler
無疑是一個(gè)最好的例子。
二、源碼
HandlerThread
的代碼很少,我們一點(diǎn)點(diǎn)看:
int mPriority; //線程的優(yōu)先級(jí)
int mTid = -1; //線程對(duì)應(yīng)的pid,結(jié)束時(shí)為-1。
Looper mLooper; //對(duì)應(yīng)的looper
再看一下run
方法:
<!-- HandlerThread.java -->
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
第一步先調(diào)用了Looper.prepare()
方法來初始該線程的Looper
,它其實(shí)是新建了一個(gè)Looper
(這個(gè) Looper
是可以退出循環(huán)的),保存到sThreadLocal
變量當(dāng)中,這個(gè)變量是static final ThreadLocal<Looper>
類型的,也就是每個(gè)Thread
有一份不同的實(shí)例,并且在每個(gè)線程中也只允許初始化一次:
<!-- Looper.java -->
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
之后拿出這個(gè)新建的Looper
保存起來,同時(shí)設(shè)置線程的優(yōu)先級(jí),接著調(diào)用Looper.loop()
方法,在這之前會(huì)回調(diào)給onLooperPrepared
,因?yàn)槿绻?code>Looper.loop()開始執(zhí)行后,那么就是一個(gè)無限循環(huán),用戶沒法進(jìn)行初始化操作了:
<!-- Looper.java -->
public static void loop() {
final Looper me = myLooper();
if (me == null) {
//exception;
}
final MessageQueue queue = me.mQueue;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
//這里面會(huì)調(diào)用 nativePollOnce(ptr, nextPollTimeoutMillis) 等待有新的消息出現(xiàn),否則就一直阻塞在這里;
Message msg = queue.next();
//如果新的消息為null,那么就退出這個(gè)循環(huán)。
if (message == null) {
return;
}
//分發(fā)有效的消息。
msg.target.dispatchMessage(msg);
msg.recycleUnchecked();
}
}
<!-- MessageQueue.java -->
Message next() {
final long ptr = mPtr;
if (ptr == null) {
return null;
}
for (;;) {
//會(huì)休眠在這里,直到通過mPtr被喚醒。
nativePollOnce(ptr, nextPollTimeoutMillis);
//被喚醒后,從隊(duì)列中去除消息進(jìn)行處理。
}
}
接下來看一下getLooper()
方法,如果此時(shí)mLooper
還沒有被初始化,那么它會(huì)一直休眠在這里:
<!-- HandlerThread.java -->
public Looper getLooper() {
//如果線程沒有存活,那么退出。
if (!isAlive()) {
return null;
}
synchronized (this) {
//如果線程存活,但是沒有開始運(yùn)行,那么等待。
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {}
}
}
return mLooper;
}
這下來看一下退出的兩個(gè)方法,它們的區(qū)別就是safe
方法會(huì)保證當(dāng)前隊(duì)列當(dāng)中的Message
都被執(zhí)行完畢,但那些delay
的消息不會(huì)被遞送。
<!-- HandlerThread.java -->
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
quit
其實(shí)是調(diào)用了和Looper
關(guān)聯(lián)的MessageQueue
對(duì)應(yīng)的quit(boolean safe)
方法:
<!-- Looper.java -->
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
<!-- MessageQueue.java -->
void quit(boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException("Main thread not allowed to quit.");
}
synchronized (this) {
if (mQuitting) {
return;
}
mQuitting = true;
if (safe) {
removeAllFutureMessagesLocked();
} else {
removeAllMessagesLocked();
}
//喚醒循環(huán),使得 loop 知道,mQuitting 的變化
nativeWake(mPtr);
}
}
可以看到這里把mQuitting
置為了true
,之后通過nativeWake
使Message.next()
中 原先阻塞的 nativePollOnce
繼續(xù)往下執(zhí)行并且會(huì)返回null
,當(dāng)Looper.loop()
中的queue.next()
返回null
,那么 Looper.loop()
也跟著退出了。
由此可見當(dāng)我們實(shí)例化一個(gè)HandlerThread
對(duì)象,之后又調(diào)用了quitXXX
方法,那么它就停止了這個(gè)循環(huán),相當(dāng)于這個(gè)Looper
對(duì)象在這個(gè)線程中雖然存在,但是無法通過它做任何操作了,即使我們第二次執(zhí)行它的run
方法,調(diào)用Looper.prepare()
的時(shí)候,也會(huì)因?yàn)?code>sThreadLocal.get() != null而拋出異常。
三、結(jié)論
可以看到,HandlerThread
就是創(chuàng)建了一個(gè)線程,當(dāng)我們調(diào)用它的start()
方法時(shí),也就是執(zhí)行它的run
方法,其實(shí)就是創(chuàng)建一個(gè)與他相關(guān)聯(lián)的Looper
,并讓這個(gè)Looper
跑起來,這個(gè)Looper
中所有消息的處理都是在這個(gè)新建的線程當(dāng)中的,調(diào)用者可以通過這個(gè)Looper
進(jìn)行后續(xù)的操作。