你真的瞭解Android的Handler機制嗎?

在Android系統中,Handler機制應用較廣,尤其是在App層面,基本每個App都會用到。使用的場景主要是向主線程發送事件,更新UI。但大家真的瞭解Handler機制嗎?看一下面的幾個問題是否可以回答:
a.Handler是如何實現多個線程之前事件傳遞的?
b.Handler、Message、MessageQueue、Looper相互之間的數量比是多少,都是1:1嗎?
c.每個變量運行的線程是那個?
d.ThreadLocal是怎麼回事,在Handler機制中起什麼作用?
能準確回答上述問題,說明對Handler機制的理解已相當到位了。
    下面論述一下Handler機制各類的實現原理,從而揭露內部的工作流程。(源碼環境爲Android8.0)
1. 先來看Handler類:
1.1 構造方法:
Handler的構造方法總共有如下幾個,最終實現爲下面兩個方法:
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}

mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
最終都調至Handler(Callback callback, boolean async)和Handler(Looper looper, Callback callback, boolean async),看一下源碼可知,主要爲初始化幾個變量:mLooper、mQueue、mCallback,mAsynchronous,前三個變量非常重要,有以下幾個結論:
a.一個Handler中含有一個Looper
b.Handler中持有的MessageQueue源於Looper中,與Looper中該變量行爲一致
c.一個Handler中含有一個Callback
Handler中還有如下幾個重要的方法,提供了Handler對外的能力:
1.2 obtainMessage方法,對外提供一個獲取Message緩存池中Message的方法,避免應用產生過多的Message對象。根據參數的不同,重載有多個該方法,實現原理都一樣,以其中之一分析一下:
// obtainMessage@Handler.java
public final Message obtainMessage()
{
return Message.obtain(this);
}
public static Message obtain(Handler h) {
Message m = obtain();
m.target = h;

return m;
}
// obtain@Message.java
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
sPool提供複用功能的實現,其存儲結構爲鏈表,通過sPoolSize的大小及SPool頭部指針位置作到這一點,感興趣的同學可以研究下
1.3 post方法、sendMessage方法,Handler提供了多個post方法,按參數不同,提供了諸如指定時間、延時的功能,基本功能是一樣的,以其中某一個方法說一下其實現:
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
從getPostMessage方法可以看出,傳入的Runnable被Message所持有。
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
由上面可知如下結論:
a.post方法的實現是與sendMessage一致的,最終都調至sendMessage中
b.幹了個什麼事呢:得到一個message,將它的callback設爲傳入的callback(如果有的話),將它的target設爲自身,然後調用MessageQueue的enqueueMessage處理該Message,實現原理講到MessageQueue再行討論。
1.4 dispatchMessage方法,該方法從Handler發起流程中難以看到在什麼地方調用了,是一個消息處理時的回調,先講一下該方法的邏輯,後面再說調用時機
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
private static void handleCallback(Message message) {
message.callback.run();
}
從上面的邏輯中看到如下結論:
消費該Hanlder事件總共有三種可能的途徑,分別爲Message中的callback、Handler所持有的Callback對象、Handler的自身的handleMessage方法(一般寫法是構造匿名子類,實現該方法),三種途徑的優先級從高到低。
Handler在該機制中的作用爲:
a.對外提供可複用的Message
b.對外提供發消息的接口
c.對外提供回調的實現,三種方式
2.Looper類
在主線程中使用Handler,看不到Looper,因爲系統已經幫我們自動生成了Looper,在工作線程中使用Handler則必須先調用Looper的prepare生成Looper,否則會報錯,原因如下:
測試代碼:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Handler handler = new Handler();
}
});
t.start();
運行後報錯:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Handler最終會調至(1.1中第一個構造方法)
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
因此正確的寫法爲:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Handler handler = new Handler();
// ignore
Looper.loop();
}
});
2.1 prepare方法:
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));
}
sThreadLocal變量定義如下:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
使用ThreadLocal類對Looper進行了一層封裝。
像c++的內聯函數一樣,此處我們直接內聯一下ThreadLocal這個類,看一下該類的作用,先從Looper中跳出去一下

--------------------------------此處插入ThreadLocal類----------------------------------
3. ThreadLocal類
ThreadLocal達到的目的是:每一個ThreadLocal的變量在多個線程中都有一份copy,相互間獨立存儲,互不影響,但變量名只有一個。也就是說對於該變量的使用方來講,看起來像是隻定義了一個變量,但實際上在多線程環境中,有互不影響的、每個線程都有一份的對象存在。如何作到這一點呢,是通過其對外提供的get方法和set方法做到的。
3.1 先來看set方法:
public void set(T value) {
Thread t = Thread.currentThread();
// 第一步,拿到每個線程所對應的ThreadLocalMap
ThreadLocalMap map = getMap(t);
// 第二步,將該值存入或更新map的對應位置
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
// ThreadLocalMap的構造方法
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
// set@ThreadLocalMap
private void set(ThreadLocal<?> key, Object value) {

// We don't use a fast path as with get() because it is at
// least as common to use set() to create new entries as
// it is to replace existing ones, in which case, a fast
// path would fail more often than not.

Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);

for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();

if (k == key) {
e.value = value;
return;
}

if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}

tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
上述邏輯第一步拿到每個線程的ThreadLocalMap對象
// threadlocals#Thread
ThreadLocal.ThreadLocalMap threadLocals = null;
也就是說每個線程維護一個ThreadLocalMap來存儲該線程所用到的所有ThreadLocal變量,ThreadLocalMap的實現原理與HashMap基本一致,之前討論過HashMap的實現原理,感興趣的同學對比一下源碼就能明白。
第二步中將傳入的值存入ThreadLocalMap的對應位置,該位置的key由ThreadLocal本身的hash值去運算得到的。從上面的代碼中可以看出。每一個線程持有一個ThreadLocalMap,set的value將和ThreadLocal自身組成key-value結構存在於該Map中。
3.2 get方法
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
理解了set方法之後,get方法就較爲簡單了,反向拿到存入的值即可,ThreadLocal對象本身在多個線程中只有一份,但通過其set和get,可以得到其包裝對象在每個線程中只有一份。
--------------------------ThreadLocal分析完畢,回至Looper----------------------------------
Looper的prepare爲一個靜態方法,目的是可以生成每個線程都有一份的Looper
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));
}
2.2 Looper構造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
持有一個MessageQueue對象,持有當前的線程對象
2.3 loop方法
public static void loop() {
// 第一步:myLooper的實現看下方,得到當前線程的Looper
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;

// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
// 第二步:定義一個無限循環體,遍歷MessageQueue,取其中的有效Message,進行處理,處理語名爲:msg.target.dispatchMessage(msg);該方法請看上面1.4
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}

// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}

final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg);
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}

if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}

// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
// 此處實現Message的循環利用
msg.recycleUnchecked();
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
在loop的處理中,有一點需重點關注,loop在線程中是一個無限循環,跳出該循環的條件爲MessageQueue的next返回值爲空,看一下4.2的next方法實現,返回空依賴於mQuitting變量,也就是說在線程中不需要一直等待事件時,要把MessageQueue該變量置爲true,設置入口爲quit@Looper
2.4 quit方法
public void quit() {
mQueue.quit(false);
}
//quit@MessageQueue
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);
}
}
總結一下:Looper在Handler機制中起的作用是:
a.提供每個線程唯一的實例
b.觸發MessageQueue的循環遍歷
4. MessageQueue類
顧名思義,該類需提供三個能力:
a.Message隊列存儲
b.Message入隊
c.Message出隊
Message隊列以鏈表形式存儲,其頭部指針存放於mMessages
4.1 enqueueMessage方法,該方法用於Message入隊
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}

synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}

msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
// 以下爲入隊的關鍵代碼,找到鏈表的隊尾,放入該Message
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
// 注意,入隊的時候,已經按時間次序將Message插入隊列中的合適位置
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}

// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
需要注意,在上面的入隊處理中,要按Handler傳入的執行時間插入
enqueueMessage調用的入口請查看1.3
4.2 next方法,該方法用於MessageQueue出隊
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}

int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}

nativePollOnce(ptr, nextPollTimeoutMillis);

synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
// 第一步:拿到鏈表的頭部
Message msg = mMessages;
// 第二步:取到最早入隊的有效的Message
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}

// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}

// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}

if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}

// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler

boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}

if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}

// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;

// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
next方法的調用入口位於2.3中

小結一下,通過上面的代碼講解,可以得到以下幾個結論:
1. 首先Handler對象本身位於構造Handler的當前線程,他的事件要發往那個線程,取決於構造方法傳 的Looper變量
2. MessageQueue與Looper位於Handler所要發往的工作線程中,Looper持有MessageQueue對象,MessageQueue中看不到Looper
3. Looper與線程爲1對1的關係,也就是說一個線程只有一個Looper,一個Looper只服務於一個線程,達到這個目的是通過ThreadLocal包裝Looper實現的
4. 從線程的角度講,Handler對象自身與線程沒有任何關係,它是通過Looper持有的MessageQueue實現向Looper所服務的線程事件隊列(MessageQueue)插入事件(Message)的

看一下文章開頭所說的幾個問題是不是已經有了答案:
a.Handler是如何實現多個線程之前事件傳遞的?
請看上面總結的第4點
b.Handler、Message、MessageQueue、Looper相互之間的數量比是多少,都是1:1嗎?
Handler n--1 Looper(以主線程爲例,主線程的Looper可以定義非常多Handler)
Looper持有一個MessageQueue(不可逆,看上面總結的第2點)
MessageQueue 1--n Message
c.每個變量運行的線程是那個?
Handler位於定義線程、Looper、MessageQueue位於工作線程,線程的輪詢依賴於Looper.loop
d.ThreadLocal是怎麼回事,在Handler機制中起什麼作用?
可查看代碼分析部分的第3部分

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章