如何使用HandlerThread掏击?
HandlerThread本質上是一個線程類丰滑,繼承自Thread類惯吕,但是HandlerThread有自己的Looper對象,可以進行l(wèi)ooper循環(huán)沛贪,不斷從MessageQueue中取消息陋守。那么震贵,我們?nèi)绾问褂肏andlerThread呢?
- 創(chuàng)建HandlerThread實例
// 創(chuàng)建HandlerThread的實例水评,并傳入?yún)?shù)來表示當前線程的名字猩系,此處//將該線程命名為“HandlerThread”
private HandlerThread mHandlerThread = new HandlerThread("HandlerThread");
- 啟動HandlerThread線程
mHandlerThread.start();
- 使用HandlerThread的Looper去構建Handler并實現(xiàn)其handlMessage的回調(diào)方法
private Handler mHandler;
// 該Callback方法運行于子線程,mHandler在創(chuàng)建時使用的是mHandlerThread的looper對象V性铩寇甸!
mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("Kathy","Received Message = " + msg.what + " CurrentThread = " + Thread
.currentThread().getName());
}
};
可以看出疗涉,我們將前面的創(chuàng)建的HandlerThread實例的Looper對象傳遞給了Handler拿霉,這使得該Handler擁有了HandlerThread的Looper對象,通過該Handler發(fā)送的消息咱扣,都將被發(fā)送到該Looper對象的MessageQueue中绽淘,且回調(diào)方法的執(zhí)行也是執(zhí)行在HandlerThread這個異步線程中。
值得注意的是闹伪,如果在handleMessage()執(zhí)行完成后沪铭,如果想要更新UI,可以用UI線程的Handler發(fā)消息給UI線程來更新偏瓤。
舉個Simple的例子
請看以下代碼:
/**
* Created by Kathy on 17-2-21.
*/
public class HandlerThreadActivity extends Activity {
private HandlerThread mHandlerThread;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 創(chuàng)建HandlerThread實例并啟動線程執(zhí)行
mHandlerThread = new HandlerThread("HandlerThread");
mHandlerThread.start();
// 將mHandlerThread.getLooper()的Looper對象傳給mHandler杀怠,之后mHandler發(fā)送的消息都將在
// mHandlerThread這個線程中執(zhí)行
mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("Kathy"案腺,"Received Message = " + msg.what + " CurrentThread = " + Thread
.currentThread().getName());
}
};
//在主線程中發(fā)送一條消息
mHandler.sendEmptyMessage(1);
new Thread(new Runnable() {
@Override
public void run() {
//在子線程中發(fā)送一條消息
mHandler.sendEmptyMessage(2);
}
}).start();
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandlerThread.quit();
}
}
創(chuàng)建mHandler時傳入HandlerThread實例的Looper對象,然后分別在主線程和其他的子線程中發(fā)送空消息懂缕,猜測handleMessage()中的Log會輸出什么贸辈?
執(zhí)行結果如下:
02-21 19:37:30.395 19479-19506/? D/Kathy: Received Message = 1 CurrentThread = HandlerThread
02-21 19:37:30.396 19479-19506/? D/Kathy: Received Message = 2 CurrentThread = HandlerThread
可知,無論是在主線程中發(fā)送消息颤陶,還是在其他子線程中發(fā)送消息,handleMessage()方法都在HandlerThread中執(zhí)行。
源碼角度解析HandlerThread
HandlerThread的源碼結構很簡單褪储,行數(shù)也不多,推薦大家自己去SDK中閱讀慧域。
HandlerThread有兩個構造函數(shù)鲤竹,在創(chuàng)建時可以根據(jù)需求傳入兩個參數(shù):線程名稱和線程優(yōu)先級。代碼如下:
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
/**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* {@link android.os.Process} and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
在HandlerThread對象的start()方法調(diào)用之后昔榴,線程被啟動辛藻,會執(zhí)行到run()方法,接下來看看互订,HandlerThread的run()方法都做了什么事情吱肌?
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() {
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
在run()方法中,執(zhí)行了Looper.prepare()方法仰禽,mLooper保存并獲得了當前線程的Looper對象氮墨,并通過notifyAll()方法去喚醒等待線程纺蛆,最后執(zhí)行了Looper.loop()開啟looper循環(huán)語句。也就是說规揪,run()方法的主要作用就是完成looper機制的創(chuàng)建桥氏。Handler可以獲得這個looper對象,并開始異步消息傳遞了猛铅。
接下來看看Handler是如何獲得這個Looper對象呢字支?
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason is isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
Handler通過getLooper()方法獲取looper對象。該方法首先判斷當前線程是否啟動?如果沒有啟動奕坟,返回null祥款;如果啟動,進入同步語句月杉。如果mLooper為null刃跛,代表mLooper沒有被賦值,則當前調(diào)用線程進入等待階段苛萎。直到Looper對象被創(chuàng)建且通過notifyAll()方法喚醒等待線程桨昙,最后才會返回Looper對象。我們看到在run()方法中腌歉,mLooper在得到Looper對象后蛙酪,會發(fā)送notifyAll()方法來喚醒等待的線程。
Looper對象的創(chuàng)建在子線程的run()方法中執(zhí)行翘盖,但是調(diào)用getLooper()的地方是在主線程中運行桂塞,我們無法保證在調(diào)用getLooper()時Looper已經(jīng)被成功創(chuàng)建,所以會在getLooper()中存在一個同步的問題馍驯,通過等待喚醒機制解決了同步的問題阁危。
那么,HandlerThread是如何退出的呢汰瘫?
/**
* Quits the handler thread's looper.
* <p>
* Causes the handler thread's looper to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*
* @see #quitSafely
*/
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
/**
* Quits the handler thread's looper safely.
* <p>
* Causes the handler thread's looper to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* Pending delayed messages with due times in the future will not be delivered.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p>
* If the thread has not been started or has finished (that is if
* {@link #getLooper} returns null), then false is returned.
* Otherwise the looper is asked to quit and true is returned.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*/
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
向下調(diào)用到Looper的quit()方法
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
再向下調(diào)用到MessageQueue的quit()方法:
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();
}
// We can assume mPtr != 0 because mQuitting was previously false.
nativeWake(mPtr);
}
}
可以看到狂打,無論是調(diào)用quit()方法還是quitSafely(),最終都將執(zhí)行到MessageQueue中的quit()方法混弥。
quit()方法最終執(zhí)行的removeAllMessagesLocked()方法趴乡,該方法主要是把MessageQueue消息池中所有的消息全部清空,無論是延遲消息(延遲消息是指通過sendMessageDelayed或通過postDelayed等方法發(fā)送)還是非延遲消息蝗拿。
quitSafely()方法晾捏,其最終執(zhí)行的是MessageQueue中的removeAllFutureMessagesLocked方法,該方法只會清空MessageQueue消息池中所有的延遲消息哀托,并將消息池中所有的非延遲消息派發(fā)出去讓Handler去處理完成后才停止Looper循環(huán)惦辛,quitSafely相比于quit方法安全的原因在于清空消息之前會派發(fā)所有的非延遲消息。最后需要注意的是Looper的quit方法是基于API 1萤捆,而Looper的quitSafely方法則是基于API 18的裙品。