一 Android的消息機(jī)制概述
簡(jiǎn)介:Android的消息機(jī)制主要是指Handle的運(yùn)行機(jī)制,Handle的運(yùn)行需要底層的MessageQueue和Looper的支撐额获;所以說(shuō)Android的消息機(jī)制主要就是指Handle的運(yùn)行機(jī)制以及Handle所附帶的MessageQueue 和 Looper的工作過(guò)程,這三者實(shí)際上是一個(gè)整體银受。
由于Android規(guī)定訪問(wèn)UI只能在主線程中進(jìn)行奋岁,如果子線程中訪問(wèn)UI,就會(huì)拋出異常 环础,子線程不能訪問(wèn)UI囚似,iOS也是一樣的;
延伸出一個(gè)問(wèn)題:
- 為什么系統(tǒng)不允許在子線程中訪問(wèn)UI呢线得?
因?yàn)閁I線程是不安全的饶唤,如果多線程中并發(fā)訪問(wèn)可能會(huì)導(dǎo)致UI控件處于不可預(yù)期的狀態(tài) - 為什么系統(tǒng)不對(duì)UI控件的訪問(wèn)加上鎖機(jī)制呢?
首先加上鎖機(jī)制會(huì)讓UI訪問(wèn)的邏輯變得復(fù)雜贯钩,其次鎖機(jī)制會(huì)降低訪問(wèn)UI的效率募狂,因?yàn)殒i機(jī)制會(huì)阻塞某些線程的執(zhí)行。鑒于這兩個(gè)缺點(diǎn)角雷,最簡(jiǎn)單切高效的方法就是采用單線程模型來(lái)處理UI操作祸穷,那也就是通過(guò)Handle切換一下UI訪問(wèn)的執(zhí)行線程即可
Handle的工作原理如下圖
Handler創(chuàng)建完畢后,這個(gè)時(shí)候其內(nèi)部的Looper以及messageQueue就可以和Handler一起協(xié)同工作了谓罗,通過(guò)Handler的post方法講一個(gè)Runnable投遞到Handler內(nèi)部的Looper處理粱哼,也可以通過(guò)Handler的send方法發(fā)送一個(gè)消息,這個(gè)消息同樣會(huì)在Looper中去處理檩咱,其實(shí)Post方法最終也是通過(guò)send方法來(lái)完成的揭措,當(dāng)Handler的send方法被調(diào)用時(shí)胯舷,他會(huì)調(diào)用MessageQueue的enqueueMessage方法將這個(gè)消息放入消息隊(duì)列中,然后Looper發(fā)現(xiàn)有新消息到來(lái)時(shí)绊含,就會(huì)處理這個(gè)消息桑嘶,最終消息中的Runnable或者Handler的handleMessage方法就會(huì)被調(diào)用。注意Looper是運(yùn)行在Handler所在的線程中的躬充,這樣一來(lái)Handler中的業(yè)務(wù)邏輯就會(huì)被切換到創(chuàng)建Handler所在的線程中去執(zhí)行了如上圖逃顶。
二 Android的消息機(jī)制分析
2.1 ThreadLocal的工作原理
簡(jiǎn)介: ThreadLocal是一個(gè)線程內(nèi)部的數(shù)據(jù)存儲(chǔ)類(lèi),通過(guò)它可以在指定的線程中存儲(chǔ)數(shù)據(jù)充甚,數(shù)據(jù)存儲(chǔ)以后以政,只有在指定線程中可以獲取存儲(chǔ)的數(shù)據(jù),對(duì)于其他線程來(lái)說(shuō)則無(wú)法獲取到數(shù)據(jù)伴找。
作用: 一般來(lái)說(shuō)盈蛮,當(dāng)某些數(shù)據(jù)是已線程為作用域并且不同線程具有不同的數(shù)據(jù)副本的時(shí)候,就可以考慮采用ThreadLocal
例子演示
// 定義一個(gè)ThreadLocal對(duì)象技矮,這里選擇Boolean類(lèi)型的
private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<Boolean>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread);
// 主線程設(shè)為 true
mBooleanThreadLocal.set(true);
Log.d(TAG, "[Thread#Main] mBooleanThreadLocal = " + mBooleanThreadLocal.get());
// 子線程設(shè)為 false
new Thread("Thread#1") {
@Override
public void run() {
mBooleanThreadLocal.set(false);
Log.d(TAG, "[Thread#1] mBooleanThreadLocal = " + mBooleanThreadLocal.get());
}
}.start();
// 子線程不設(shè)置
new Thread("Thread#2") {
@Override
public void run() {
Log.d(TAG, "[Thread#2] mBooleanThreadLocal = " + mBooleanThreadLocal.get());
}
}.start();
結(jié)果為
D/ThreadActivity: [Thread#Main] mBooleanThreadLocal = true
D/ThreadActivity: [Thread#1] mBooleanThreadLocal = false
D/ThreadActivity: [Thread#2] mBooleanThreadLocal = null
可以看出不同線程中訪問(wèn)的是同一個(gè)ThreadLocal對(duì)象抖誉,但是他們通過(guò)ThreadLocal獲取到的值確實(shí)不一樣的,是因?yàn)椴煌€程訪問(wèn)同一個(gè)ThreadLocal的get方法衰倦,ThreadLocal內(nèi)部會(huì)從各自的線程中取出一個(gè)數(shù)組袒炉,然后從數(shù)組中根據(jù)當(dāng)前ThreadLocal的索引去查找主對(duì)應(yīng)的Value的值
ThreadLocal 內(nèi)部實(shí)現(xiàn)原理:
set方法
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
首先會(huì)通過(guò)getmap方法獲取當(dāng)前線程的ThreadLocalMap數(shù)據(jù),如果ThreadLocalMap值為null樊零,那就就對(duì)其初始化我磁,并存入value值。ThreadLocalMap內(nèi)部有一個(gè)數(shù)組 Entry[] table淹接,ThreadLocal就存在這個(gè)數(shù)組里邊十性,那我們來(lái)看一下這個(gè)ThreadLocalMap是如何使用set方法將ThreadLocal存入到table數(shù)組中的
ThreadLocalMap的set方法
private void set(ThreadLocal<?> key, Object value) {
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();
}
我們可以看出threadLocal的值在tabble數(shù)組中的存儲(chǔ)位置總是為threadLocal的 Referent字段所標(biāo)識(shí)的對(duì)象的下一個(gè)位置
ThreadLocalMap的get方法:
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();
}
2.2 消息隊(duì)列的工作原理
簡(jiǎn)介: 消息隊(duì)列在Android中指的是MessageQueue,包含兩個(gè)操作:插入(enqueueMessage)和讀人艿俊(next);盡管MessageQueue叫做消息隊(duì)列劲适,但是他的內(nèi)部實(shí)現(xiàn)原理用的卻是單鏈表,其源碼如下
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;
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;
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;
}
從enqueueMessage的實(shí)現(xiàn)來(lái)看,他的主要操作其實(shí)就是單鏈表的插入操作
Next方法的源碼
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;
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方法就是一個(gè)無(wú)線循環(huán)的方法厢蒜,如果消息隊(duì)列中沒(méi)有消息霞势,那么Next方法一直阻塞在這里,當(dāng)有新消息到來(lái)時(shí)斑鸦,next方法會(huì)返回這條消息并將其從單鏈表中移除
2.3 Looper的工作原理
簡(jiǎn)介: Looper在Android的消息機(jī)制中扮演者消息循環(huán)的角色愕贡,就是會(huì)不停的從MessageQueue中查看是否有新消息如果有新消息,就會(huì)立刻處理巷屿;否則則阻塞在那里
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以通過(guò)Looper.prepare() 為當(dāng)前線程創(chuàng)建一個(gè)Looper固以,接著通過(guò)Looper.loop來(lái)開(kāi)啟消息循環(huán)
new Thread("Thread#1") {
@Override
public void run() {
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
}.start();
需要注意:
- looper還提供了prepareMainLooper方法,給主線程創(chuàng)建Looper使用的,本質(zhì)也是prepare方法實(shí)現(xiàn)
- Looper提供了一個(gè)getMainLooper方法憨琳,可以在任何地方獲取到主線程的Looper
- Looper可以退出quite和quitSafely方法诫钓,quite會(huì)直接退出Looper,而quitSafely會(huì)把消息隊(duì)列中的已有消息處理完畢后才安全退出篙螟,
- 子線程創(chuàng)建的Looper菌湃,在消息處理完畢后要手動(dòng)調(diào)用quit方法來(lái)終止消息循環(huán)
Looper的loop方法:
只有調(diào)用了loop方法后,消息循環(huán)系統(tǒng)才會(huì)真正的起作用,loop方法是一個(gè)死循環(huán)遍略,唯一跳出循環(huán)的方式是MessageQueue的next方法返回null惧所,loop方法會(huì)調(diào)用MessageQueue的next方法來(lái)獲取新消息,而next方法是一個(gè)阻塞操作绪杏,當(dāng)沒(méi)有消息是下愈,next方法會(huì)一直阻塞在那里,這也就導(dǎo)致loop方法一直阻塞在那里蕾久,MessageQueue的next方法返回新消息驰唬,Looper就會(huì)處理這條消息
如下源碼
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();
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);
}
msg.recycleUnchecked();
}
}
2.4 Handle的工作原理
簡(jiǎn)介:Handle的工作主要包含消息的發(fā)送和接受過(guò)程。消息的發(fā)送可以通過(guò)Post的一系列方法以及Send的一系列方法來(lái)實(shí)現(xiàn)腔彰,Post方法最終也是通過(guò)send方法來(lái)實(shí)現(xiàn)的;
來(lái)看一下源碼
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
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);
}
由源碼可以看出辖佣,Handler發(fā)送消息的過(guò)程僅僅是向消息隊(duì)列中插入了一條消息霹抛,MessageQueue的next方法就會(huì)返回這條消息給Looper,Looper收到消息后就開(kāi)始處理了卷谈,最終消息由Looper交由Handler處理杯拐,即Handler的dispatMessage方法會(huì)被調(diào)用,這時(shí)候Handler就進(jìn)入了處理消息的階段世蔗。
dispatMessage的實(shí)現(xiàn)源碼如下:
public void dispatchMessage(Message msg) {
// 檢查是否為空
if (msg.callback != null) {
// callback是一個(gè)Runnable對(duì)象端逼,實(shí)際上就是Handler的post方法所傳遞的Runnable參數(shù)。
handleCallback(msg);
} else {
// 檢查mCallback 是否為空污淋,
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
// 最后來(lái)處理消息
handleMessage(msg);
}
}
Handler還有一個(gè)特殊的構(gòu)造方法顶滩,那就是通過(guò)一個(gè)特定的Looper來(lái)構(gòu)造Handler,他的實(shí)現(xiàn)如下所示:
public Handler(Looper looper) {
this(looper, null, false);
}
Handler的默然構(gòu)造方法 public Handler()寸爆, 這個(gè)構(gòu)造方法會(huì)調(diào)用下面的構(gòu)造方法礁鲁。
也解釋了在沒(méi)有Looper的子線程中創(chuàng)建Handler會(huì)引發(fā)程序異常的原因了
public Handler(Callback callback, boolean async) {
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;
}
三 主線程的消息循環(huán)
簡(jiǎn)介 Android的主線程就是ActivityThread,主線程的入口方法為main赁豆,在main方法中系統(tǒng)會(huì)通過(guò)Looper.prepareMainLooper() 來(lái)創(chuàng)建主線程的Looper以及MessageQueue仅醇,并通過(guò)Looper.loop() 來(lái)開(kāi)啟主線程的消息循環(huán)
public static void main(String[] args) {
...............
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
Looper.loop();
................
主線程的消息循環(huán)開(kāi)始以后,ActivityThread還需要一個(gè)Handler來(lái)和消息隊(duì)列進(jìn)行交互魔种,這個(gè)Handler就是ActivityThread.H 他內(nèi)部定義了一組消息類(lèi)型析二,主要包含四大組件的啟動(dòng)和停止等過(guò)程;
ActivityThread通過(guò)ApplicationThread和AMS進(jìn)行進(jìn)程間通信节预,AMS已進(jìn)程間通信的方式完成ActivityThread的請(qǐng)求后會(huì)回調(diào)ApplicationThread中的Binder方法叶摄,然后ApplicationThread會(huì)向H發(fā)送消息属韧,H收到消息后會(huì)將ApplicationThread中的邏輯切換到ActivityThread去執(zhí)行,即切換到主線程中去執(zhí)行准谚,這個(gè)過(guò)程就是主線程的消息循環(huán)模型
參考資料:
《Android開(kāi)發(fā)藝術(shù)探索》