1.handler的簡(jiǎn)易模型
2.handler的幾個(gè)關(guān)鍵人物,message,messageQueue,handler,looper,(每個(gè)角色是干啥,是啥數(shù)據(jù)結(jié)構(gòu))。
3.詳細(xì)原理
Handler是如何實(shí)現(xiàn)子線程發(fā)送消息,主線程處理消息的?
很多源碼分析都分析的很詳細(xì),可往往最本質(zhì)的東西卻沒講清楚。
其實(shí)原理很簡(jiǎn)單,有一個(gè)共享集合,主線程在無(wú)限循環(huán)取集合里面的消息,取到消息就分發(fā)執(zhí)行消息,而子線程往集合里面添加數(shù)據(jù)(子線程添加一個(gè),主線程就能取出來(lái),主線無(wú)限循環(huán)取消息,像個(gè)饑渴男),這樣就間接實(shí)現(xiàn)了線程間通信。
實(shí)現(xiàn)過程
1.使用:我們通常都是
// 1:在主線程中創(chuàng)建Handler類對(duì)象
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
...// 主線程處理消息
}
};
//2:子線程發(fā)消息
Message msg = Message.obtain(); // 創(chuàng)建消息對(duì)象
msg.what = 0; // 標(biāo)識(shí)
msg.obj = "obj"; // 內(nèi)容
handler .sendMessage(msg);//發(fā)送消息
2.對(duì)照模型分析
1.存消息的集合是誰(shuí)?在handler的構(gòu)造方法中,我們一目了然,給handler指定了一個(gè)叫Looper的對(duì)象(looper為空會(huì)報(bào)錯(cuò)),并把Looper的mQueue賦值給了handler的mQueue ,這個(gè)mQueue 就是存消息的(MessageQueue),這里有個(gè)地方要留意,handler是和looper綁定的,而取looper是用的Looper.myLooper();是一個(gè)靜態(tài)方法,你進(jìn)去就會(huì)發(fā)現(xiàn)
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
這個(gè)sThreadLocal是Looper的成員
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
我們好像沒有調(diào)用過looper.prepare(),先看方法
private static void prepare(boolean quitAllowed) {
//sThreadLocal里面有一個(gè)ThreadLocalMap,用于將當(dāng)前線程和looper綁定
if (sThreadLocal.get() != null) {
//當(dāng)前線程已經(jīng)綁定了一個(gè)looper,不能多次綁定
throw new RuntimeException("Only one Looper may be created per thread");
}
//綁定當(dāng)前線程的looper
sThreadLocal.set(new Looper(quitAllowed));
}
到這里,handler和looper綁定,looper和當(dāng)前線程綁定,而且創(chuàng)建handler時(shí),要保證當(dāng)前線程的looper不能為空,那我們創(chuàng)建handler之前得調(diào)用Looper.prepare();
現(xiàn)在我們換種玩法
Handler handler=null;
@Test
public void one() throws InterruptedException {
//線程A
new Thread("A"){
@Override
public void run() {
super.run();
Looper.prepare();//創(chuàng)建并綁定looper
handler =new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println("我收到了消息!"+currentThread().getName());
}
};
Looper.loop();//開啟循環(huán)
}
}.start();
new Thread("B"){
@Override
public void run() {
super.run();
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Message msg=Message.obtain();
if (handler!=null){
handler.sendMessage(msg);
System.out.println("B發(fā)了消息"+currentThread().getName());
}
}
}.start();
Thread.sleep(5000);
}
運(yùn)行結(jié)果
Started running tests
I/System.out: B發(fā)了消息B
I/System.out: 我收到了消息!A
上面列子注意的地方
1.new Handler(),里面可以帶參數(shù),可以傳入要指定的looper,比如Looper.getMainLooper(),這樣我們的handler就和綁定在主線程的looper綁定了。
2.Looper.loop();這個(gè)方法是開啟消息循環(huán),可理解為線程A進(jìn)入無(wú)線循環(huán)取消息模式,當(dāng)取出消息時(shí),執(zhí)行msg.target.dispatchMessage(msg);target就是一個(gè)handler,sendMessage()最終調(diào)用enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis),這里將msg和handler綁定。這里就好理解了,在looper中,循環(huán)取到消息,然后分發(fā)執(zhí)行消息,所以handleMessage()方法執(zhí)行在Looper.loop();開啟的地方所在的線程,
3.MessageQueue存消息用到enqueueMessage(),取消息是next(),取消息會(huì)用到一個(gè)native方法nativePollOnce(ptr, nextPollTimeoutMillis);,這個(gè)方法不會(huì)影響性能,當(dāng)messageQueue里面沒有消息,這個(gè)方法會(huì)讓Looper所在的線程進(jìn)入等待狀態(tài),釋放cpu資源(詳細(xì)介紹網(wǎng)上有很多)。
小結(jié)
到這里其實(shí)handler的一套基本走完了,還有發(fā)送消息的封裝,兩種發(fā)消息的區(qū)別,以及對(duì)應(yīng)處理消息的源碼都很好理解。至于主線程何時(shí)調(diào)用的Looper.prepare(),是在ActivityThread的main()方法中,一開始就為主線程綁定了looper。
- Handler在子線程A中創(chuàng)建并綁定線程A的looper,然后在A線程中開啟循環(huán)取消息,這樣取消息,處理消息都執(zhí)行在A線程
- 線程B中發(fā)送消息
最后
要看源碼,還是自己搓進(jìn)去看最直觀,這里只點(diǎn)出了關(guān)鍵的方法和大致流程,里面還有很多細(xì)節(jié)沒講,最后忍不住貼上兩種發(fā)消息的方法
//1sendMessage->sendMessageDelayed->sendMessageAtTime
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);
}
//2post
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;//封裝成一個(gè)帶callback的msg
}
//3處理消息
public void dispatchMessage(Message msg) {
//根據(jù)是否有callback來(lái)判斷是post還是sendMsg
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
附錄(類里面要注意的東西)
Handler
- mLooper : Looper
- mQueue : MessageQueue
Looper
- sThreadLocal : ThreadLocal
- sMainLooper : Looper
- mQueue : MessageQueue
- mThread : Thread
- prepare()
- preparMainLooper()
- myLooper()
- looper()*
Message
- target : Handler
MessageQueue
- next()
- enqueueMessage()
handlerThread就是封裝了handler的thread,很少用到。