Handler機(jī)制算是個(gè)老生常談的問題了裹赴,最近又看了下源碼,決定還是形成文字記錄下來靠譜诀浪。
1棋返、handler
handler在Android用于不同線程間的通信。使用時(shí)雷猪,一般會(huì)在主線程(接收消息的線程)new一個(gè)handler睛竣,那就先看下handler的源碼:
public Handler(Callback callback, boolean async) {
...
//獲取Looper
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;
}
從該構(gòu)造方法可以得到以下幾個(gè)信息:
1、Handler對(duì)象依賴于Looper對(duì)象求摇。
2射沟、Looper對(duì)象中當(dāng)中持有mQueue對(duì)象。
3与境、Looper中的mQueue對(duì)象賦給了Handler成員變量验夯。
3、Looper.prepare()用來創(chuàng)建Looper對(duì)象摔刁,有了Looper對(duì)象后才能創(chuàng)建Handler挥转。
這里引出了Looper這個(gè)概念,讓我們看下Looper是什么吧共屈。
2绑谣、Looper
Looper的創(chuàng)建,即上面提到的Looper.prepare()方法:
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));
}
Looper的獲绒忠:
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static Looper myLooper() {
return sThreadLocal.get();//從ThreadLocal中獲取
}
Looper的構(gòu)造方法:
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
該構(gòu)造函數(shù)為私有的借宵,也就是說Looper只能由它的靜態(tài)方法prepare創(chuàng)建。構(gòu)造方法內(nèi)創(chuàng)建了MessageQueue對(duì)象矾削。
那么Looper又是什么呢壤玫,它有啥用豁护?看下源碼的注釋:
Class used to run a message loop for a thread. Threads by default do
not have a message loop associated with them; to create one, call
{@link #prepare} in the thread that is to run the loop, and then
{@link #loop} to have it process messages until the loop is stopped.
簡(jiǎn)單的說明下Looper是用來和Thread綁定的,它的內(nèi)部維護(hù)了一個(gè)消息隊(duì)列mQueue垦细,所有發(fā)送給Thread的消息都會(huì)進(jìn)入這個(gè)隊(duì)列择镇,然后Looper會(huì)循環(huán)處理這些消息。
看到這里括改,我們會(huì)有幾個(gè)疑問:
1、Looper的創(chuàng)建和獲取方法中引入了sThreadLocal家坎,這是什么嘱能?
2、Looper如何與Thread綁定的虱疏?
3惹骂、Looper是如何接收消息,如何將消息存入它內(nèi)部的消息隊(duì)列mQueue的做瞪?
4对粪、Looper是如何處理消息的?
下面就帶著這幾個(gè)疑問装蓬,依次解決著拭。
3、ThreadLocal
首先講下handler的作用牍帚,當(dāng)然相信大家都懂得:假設(shè)有兩個(gè)線程MainThread和SubThread儡遮。SubThread中通過獲取在MainThread中創(chuàng)建的Handler對(duì)象,調(diào)用Handler的post或sendMessage方法暗赶,將消息傳遞給MainThread后并在該線程中處理鄙币。
由上面對(duì)Looper的介紹,我們又知道蹂随,實(shí)質(zhì)上十嘿,發(fā)送的消息,最終交給了與MainThread綁定的Looper對(duì)象中的mQueue隊(duì)列岳锁。最終的消息處理也是由這個(gè)Looper調(diào)度的绩衷。
如果讓我們自己設(shè)計(jì)這樣一個(gè)功能,不難想到浸锨,如果一個(gè)Looper綁定了多個(gè)Thread唇聘,那么Looper在接收到消息后處理,該在哪個(gè)線程中執(zhí)行呢柱搜?所以每個(gè)Looper對(duì)象應(yīng)只綁定一個(gè)線程迟郎,即每個(gè)Looper都是被某個(gè)線程獨(dú)占的。
事實(shí)上源碼就是這么設(shè)計(jì)聪蘸,且每個(gè)Thread中只有一個(gè)Looper對(duì)象宪肖。
源碼中為了保證每個(gè)Thread都有它獨(dú)立的Looper表制,采用了ThreadLocal。
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).
Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).
用中文概括下來講控乾,就是對(duì)于同一類型的對(duì)象傳給ThreadLocal后么介,ThreadLocal提供了一個(gè)綁定策略,它會(huì)將該對(duì)象綁定至當(dāng)前的線程中蜕衡,最終使得每個(gè)Thread中該類型的對(duì)象都是獨(dú)立的壤短,互不影響。
如果不太了解的話慨仿,可以參考這篇文章:http://www.reibang.com/p/95291228aff7久脯,看下文章開頭的示例大概就明白了。
用在這里镰吆,就是ThreadLocal能夠讓每個(gè)Thread中都擁有獨(dú)立的Looper對(duì)象帘撰。ThreadLocal是怎樣實(shí)現(xiàn)這一魔法的,看源碼:
Looper內(nèi)持有靜態(tài)且final的sThreadLocal成員變量万皿。
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
在prepare方法中摧找,創(chuàng)建新的Looper對(duì)象,并傳給sThreadLocal牢硅。
sThreadLocal.set(new Looper(quitAllowed));
ThreadLocal中:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
//this蹬耘,本類對(duì)象,如果結(jié)合Looper源碼唤衫,這里的this就是指sThreadLocal婆赠。
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);
}
從源碼可以看出,set方法內(nèi)首先獲取當(dāng)前Thread內(nèi)的ThreadLocalMap佳励,如果不存在休里,就先創(chuàng)建。到Thread源碼內(nèi)驗(yàn)證一下赃承,果然有個(gè)ThreadLocal.ThreadLocalMap類型的threadLocals 成員變量妙黍。從名字xxxMap可以看出,這個(gè)成員變量是以鍵值對(duì)形式存儲(chǔ)數(shù)據(jù)的瞧剖。
結(jié)合Looper源碼拭嫁,key即為sThreadLocal,value即為L(zhǎng)ooper對(duì)象抓于。這樣做粤,對(duì)于每個(gè)Thread線程,就都會(huì)有它獨(dú)立的Looper對(duì)象了捉撮。
到這里怕品,上面提到的四個(gè)問題中1和2就解決了。
4巾遭、MessageQueue
MessageQueue是在Looper的構(gòu)造方法內(nèi)初始化的肉康,Thread和Looper是唯一綁定的闯估,所以每個(gè)Thread也只能有唯一的一個(gè)MessageQueue!MessageQueue是鏈表解構(gòu)的隊(duì)列吼和,因?yàn)橄⑿枰l繁的增刪涨薪,所以采用鏈表效率更高。
當(dāng)我們調(diào)用Handler的sendMessage或post發(fā)送一個(gè)消息時(shí)炫乓,最終都會(huì)調(diào)用:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
這里的queue就是在Looper構(gòu)造函數(shù)內(nèi)初始化的那個(gè)刚夺。
消息存入該鏈表后,Looper的loop方法就會(huì)循環(huán)遍歷這個(gè)鏈表末捣,一次取出消息光督,最后交給Handler的handleMessage取處理:
public static void loop() {
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();
//無限循環(huán),遍歷消息鏈表
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 traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
//msg.target就是發(fā)送消息時(shí)的那個(gè)handler塔粒。
//最終調(diào)用handler的handleMessage方法處理。
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
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);
}
msg.recycleUnchecked();
}
}
Looper的loop方法筐摘,會(huì)在創(chuàng)建Looper(Handler)的那個(gè)線程中調(diào)用卒茬,該方法中最關(guān)鍵的是msg.target.dispatchMessage(msg);
,target從何而來咖熟?看下Handler的enqueueMessage方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
原來msg.target就是發(fā)送消息的那個(gè)Handler本身圃酵!事件回傳給Handler的dispatchMessage處理,貼出源碼:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
是不是熟悉的方法來了馍管!如果msg是runnable事件郭赐,調(diào)用handleCallback(msg)
,最終調(diào)用runnable的run方法執(zhí)行确沸;
如果msg是普通事件捌锭,就調(diào)用 handleMessage(msg)
執(zhí)行,而handleMessage不就是我們通常會(huì)重寫的handler的方法嗎罗捎?
同時(shí)观谦,因?yàn)閘oop方法在創(chuàng)建Looper的線程中執(zhí)行,那么loop方法中的所有方法調(diào)用桨菜,都未涉及到線程切換豁状,所以也都在Looper創(chuàng)建的線程中執(zhí)行。
5倒得、畫個(gè)圖吧
想了想還是來個(gè)圖直觀點(diǎn)泻红!
6、總結(jié)
Handler這一套機(jī)制霞掺,說白了也挺簡(jiǎn)單的谊路。
1、首先需要調(diào)用Looper.prepare()根悼,為當(dāng)前線程創(chuàng)建Looper對(duì)象凶异,同時(shí)創(chuàng)建的還有MessageQueue蜀撑,ThreadLocal會(huì)用來保證每個(gè)線程擁有獨(dú)立的一套Looper和MessageQueue。
2剩彬、然后再new Handler()酷麦,它會(huì)持有剛才在線程中創(chuàng)建的Looper和MessageQueue對(duì)象,從而與線程間接關(guān)聯(lián)喉恋。(注意沃饶,一個(gè)Handler對(duì)應(yīng)一個(gè)線程,但一個(gè)線程中可以有多個(gè)Handler轻黑,但多個(gè)handler多會(huì)持有同一個(gè)Looper和MessageQueue對(duì)象)糊肤。
3、最后在同樣的線程中調(diào)用Looper.loop()循環(huán)遍歷MessageQueue鏈表氓鄙,該循環(huán)是一個(gè)阻塞方法馆揉,它會(huì)一直執(zhí)行,當(dāng)消息到來抖拦,就會(huì)依次取出消息升酣,讓后讓發(fā)送該消息的那個(gè)handler處理事件(具體怎么處理取決于我們重寫的Handler的handleMessage方法)。由于Looper.loop()方法是在創(chuàng)建Looper的那個(gè)線程中調(diào)用的态罪,所以handleMessage也會(huì)在同一線程中執(zhí)行噩茄。
4、Handler的異步消息處理機(jī)制的關(guān)鍵在于:Handler對(duì)象對(duì)每個(gè)線程都是可見的复颈,在不同線程中绩聘,可以拿到這個(gè)handler發(fā)送消息;但Handler對(duì)應(yīng)的Looper和MessageQueue卻是每個(gè)線程獨(dú)立存在的耗啦;消息最終會(huì)在創(chuàng)建Looper的那個(gè)線程中被處理凿菩,從而達(dá)到異步處理的目的。