HandlerThread源碼解析

上一篇文章對HandlerThread的概念及用法做了一個基本的介紹,并且使用HandlerThread改寫了相冊圖片加載模塊中的ImageLoader,可以看到,改寫后的代碼變得更加清晰和簡潔了。本篇文章將延續(xù)之前的主題,從源代碼層面對HandlerThread的底層原理進行深入的剖析,讓大家不僅知其然,更知其所以然,好了,話不多說,就讓我們開始今天美妙的探索之旅吧_

如果讀者已經(jīng)較好地掌握了Android異步消息處理的底層機制,那么理解HandlerThread的源碼將會變得異常簡單。對Android異步消息處理底層機制尚未完全掌握的朋友可先閱讀我之前的博文Android異步消息處理機制深度解析。

HandlerThread源碼如下:

  1 /*
  2  * Copyright (C) 2006 The Android Open Source Project
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 package android.os;
 18 
 19 /**
 20  * Handy class for starting a new thread that has a looper. The looper can then be 
 21  * used to create handler classes. Note that start() must still be called.
 22  */
 23 public class HandlerThread extends Thread {
 24     int mPriority;
 25     int mTid = -1;
 26     Looper mLooper;
 27 
 28     public HandlerThread(String name) {
 29         super(name);
 30         mPriority = Process.THREAD_PRIORITY_DEFAULT;
 31     }
 32     
 33     /**
 34      * Constructs a HandlerThread.
 35      * @param name
 36      * @param priority The priority to run the thread at. The value supplied must be from 
 37      * {@link android.os.Process} and not from java.lang.Thread.
 38      */
 39     public HandlerThread(String name, int priority) {
 40         super(name);
 41         mPriority = priority;
 42     }
 43     
 44     /**
 45      * Call back method that can be explicitly overridden if needed to execute some
 46      * setup before Looper loops.
 47      */
 48     protected void onLooperPrepared() {
 49     }
 50 
 51     @Override
 52     public void run() {
 53         mTid = Process.myTid();
 54         Looper.prepare();
 55         synchronized (this) {
 56             mLooper = Looper.myLooper();
 57             notifyAll();
 58         }
 59         Process.setThreadPriority(mPriority);
 60         onLooperPrepared();
 61         Looper.loop();
 62         mTid = -1;
 63     }
 64     
 65     /**
 66      * This method returns the Looper associated with this thread. If this thread not been started
 67      * or for any reason is isAlive() returns false, this method will return null. If this thread 
 68      * has been started, this method will block until the looper has been initialized.  
 69      * @return The looper.
 70      */
 71     public Looper getLooper() {
 72         if (!isAlive()) {
 73             return null;
 74         }
 75         
 76         // If the thread has been started, wait until the looper has been created.
 77         synchronized (this) {
 78             while (isAlive() && mLooper == null) {
 79                 try {
 80                     wait();
 81                 } catch (InterruptedException e) {
 82                 }
 83             }
 84         }
 85         return mLooper;
 86     }
 87 
 88     /**
 89      * Quits the handler thread's looper.
 90      * <p>
 91      * Causes the handler thread's looper to terminate without processing any
 92      * more messages in the message queue.
 93      * </p><p>
 94      * Any attempt to post messages to the queue after the looper is asked to quit will fail.
 95      * For example, the {@link Handler#sendMessage(Message)} method will return false.
 96      * </p><p class="note">
 97      * Using this method may be unsafe because some messages may not be delivered
 98      * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
 99      * that all pending work is completed in an orderly manner.
100      * </p>
101      *
102      * @return True if the looper looper has been asked to quit or false if the
103      * thread had not yet started running.
104      *
105      * @see #quitSafely
106      */
107     public boolean quit() {
108         Looper looper = getLooper();
109         if (looper != null) {
110             looper.quit();
111             return true;
112         }
113         return false;
114     }
115 
116     /**
117      * Quits the handler thread's looper safely.
118      * <p>
119      * Causes the handler thread's looper to terminate as soon as all remaining messages
120      * in the message queue that are already due to be delivered have been handled.
121      * Pending delayed messages with due times in the future will not be delivered.
122      * </p><p>
123      * Any attempt to post messages to the queue after the looper is asked to quit will fail.
124      * For example, the {@link Handler#sendMessage(Message)} method will return false.
125      * </p><p>
126      * If the thread has not been started or has finished (that is if
127      * {@link #getLooper} returns null), then false is returned.
128      * Otherwise the looper is asked to quit and true is returned.
129      * </p>
130      *
131      * @return True if the looper looper has been asked to quit or false if the
132      * thread had not yet started running.
133      */
134     public boolean quitSafely() {
135         Looper looper = getLooper();
136         if (looper != null) {
137             looper.quitSafely();
138             return true;
139         }
140         return false;
141     }
142 
143     /**
144      * Returns the identifier of this thread. See Process.myTid().
145      */
146     public int getThreadId() {
147         return mTid;
148     }
149 }

代碼不多,算上注釋才149行。
HandlerThread中最重要的是它的run方法和getLooper方法,我們先來看run方法:
首先掃一眼run方法,突然感覺好熟悉啊!熟悉的Looper.prepare(),熟悉的Looper.loop(),這不是我們在子線程創(chuàng)建Handler時所需要的一些操作嗎?沒錯,雖然我們在當(dāng)前的run方法里并沒有創(chuàng)建Handler,但是讀完本文,你應(yīng)該能體會到它和我們在子線程創(chuàng)建Handler的異曲同工之妙。
在run方法中,首先會去調(diào)用Looper.prepare(),Looper.prepare()會去檢查sThreadLocal中是否存儲了Looper對象,若已經(jīng)存儲了,則報異常(一個線程最多只能有一個Looper對象),若尚未存儲,則新建一個Looper對象并將其放入sThreadLocal中。之后會進入一個同步代碼塊,取出當(dāng)前的Looper對象賦給HandlerThread對象的成員變量mLooper并調(diào)用notifyAll()方法。接著便會去調(diào)用Looper.loop(),在Looper.loop()中有一個死循環(huán),會不斷地從MessageQueue中取出下一條消息,如果拿不到消息則阻塞。拿到消息后,如果消息不為空且消息的target屬性不為空,則調(diào)用消息的target屬性的dispatchMessage方法。

再來看getLooper方法,首先會調(diào)用isAlive()方法測試線程是否還活著,如果不是,則直接返回null。接著會進入一個同步代碼塊,當(dāng)線程還存活著且成員變量mLooper為null時,會執(zhí)行wait操作,等待run方法中的notifyAll(),由此可知,只要之前我們的HandlerThread被啟動了,這個方法會一直阻塞直至mLooper初始化完成,最后將初始化完成的mLooper返回出去。

通常情況下,HandlerThread啟動后,會通過getLooper()方法取出Looper對象并將其作為Handler的初始化參數(shù)。此時,getLooper()方法是運行在主線程的,而Looper對象的初始化是位于子線程(HandlerThread)的run方法中的,getLooper()方法中的 wait()與run方法中的notifyAll()共同協(xié)作,實現(xiàn)了兩個線程之間的同步。

到這里,相信大家對HandlerThread的源碼已經(jīng)有了一個非常深入的理解了,下一篇文章將介紹與HandlerThread關(guān)聯(lián)甚大的IntentService,大家一起期待吧!

參考:http://blog.csdn.net/lmj623565791/article/details/47079737

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容