消息機制主要包含三個元素:Handler、MessageQueue、Looper
工作原理
Hander被創建後,通過Handler的post方法將一個Runable投遞到Handler內部的Looper中去處理,或者通過Handler的send方法發送一個消息到Handler內部的Looper中處理,其中post方法最終也是通過send方法實現的。具體的過程是:當Handler的send方法被調用發出一個消息,MessageQueue就會將這個消息插入消息隊列中,Looper發現有新的消息(MessageQueue的next方法),就會處理這個消息。最終這個消息的Runable或者Handler的handleMessage方法就會被調用。Looper是運行在創建Handler的線程中,這樣一來Handler中的業務邏輯就會切換到創建Handler的線程中。
1、ThreadLocal
ThreadLocal是線程內部的數據存儲類,可以通過它在指定的線程中存儲數據,數據存儲後,只能指定的線程能訪問,別的線程都不能訪問。應用場景:
- 當某個數據以線程爲作用域且對於不同的線程需要不同的副本時可以選用;
- 複雜邏輯下的對象傳參。
private ThreadLocal<Boolean> mBooleanThreadLocal = new ThreadLocal<>();
mBooleanThreadLocal.set(true);
Log.d(TAG, "MainThread: " + mBooleanThreadLocal.get());
new Thread(new Runnable() {
@Override
public void run() {
mBooleanThreadLocal.set(false);
Log.d(TAG, "Thread1: " + mBooleanThreadLocal.get());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Thread2: " + mBooleanThreadLocal.get());
}
}).start();
上面的例子可以看出,不同的線程訪問同一個成員變量mBooleanThreadLocal ,MainThread設置爲 true, 調用mBooleanThreadLocal.get()得到的是true;而Thread1設置爲false,訪問到的是false;Thread2沒有設置,調用mBooleanThreadLocal.get()得到是null。不同的線程訪問同一個成員變量得到的值不一樣,這是爲什麼?看看set和get方法的實現。
①先看看set方法的實現
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
可以看到,這個方法從當前線程獲取了一個ThreadLocalMap對象,然後把值set進去,如果獲取的ThreadLocalMap對象爲空,則創建一個,再把值放進去。
接下來就該看看map.set(this, value);是如何把值放進去的
/**
* Set the value associated with key.
*
* @param key the thread local object
* @param value the value to be set
*/
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();
}
可以看到通過 int i = key.threadLocalHashCode & (len-1); 獲取一個索引,當然不同的key通過Hash散列後可能會有衝突,在這個方法中也處理了衝突的情況,也就是說存入的位置不一定是int i = key.threadLocalHashCode & (len-1);得到的i;然後將value存入ThreadLocalMap中的table數組中。
②再看一下mBooleanThreadLocal.get()這個get()方法的實現。
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
可以看到,get方法就是從ThreadLocalMap中的table數組中取出通過set方法放進去的值,如果找不到則調用setInitialValue()初始化並返回,這個初始化默認是初始化爲null。
再看看setInitialValue()其實就是爲當前線程中的一個ThreadLocalMap(就是threadLocals)設置了一個值,如果是上面的例子就是:map.set( mBooleanThreadLocal, null); ,所以我們在線程2中得到null。
結論:通過mBooleanThreadLocal.get()方法取出的是各個線程中ThreadLocalMap中的table數組中的某個索引的值,當然就不一樣啦。
下面的代碼
new Thread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Thread2: " + mBooleanThreadLocal.get());
}
}).start();
沒有先調用set方法,直接取值,返回的是setInitialValue()這個方法的返回值,即爲null,我們能不能實現一個返回一個默認的值,比如我沒有調set方法,但是我希望返回的false,而不是null。我們看看setInitialValue()的實現
/**
* Variant of set() to establish initialValue. Used instead
* of set() in case user has overridden the set() method.
*
* @return the initial value
*/
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;
}
protected T initialValue() {
return null;
}
好了,看到這裏我們就明白了爲什麼是null,而且這個方法是protected修飾的,並且返回的是泛型,我們可以重寫它來實現我們想返回的值。示例:
①我們需要寫一個類繼承ThreadLocal並重寫initalValue()方法
class MyThreadLocal extends ThreadLocal{
@Override
protected Object initialValue() {
return false;
}
}
②創建一個實例,直接調get方法,看看結果是null,還是false
private MyThreadLocal myThreadLocal = new MyThreadLocal();
Log.d(TAG, "MainThread: " + myThreadLocal.get());
③跑起來看看logcat
2、MessageQueue
MessageQueue即消息隊列,這是一個鏈式的隊列。爲什麼採用鏈式而不採用順序存儲(比如數組)。這就取決於消息隊列的特點:經常做的操作是插入,取出刪除。
順序存儲 VS 鏈式存儲
存儲方式 | 查找效率 | 插入、刪除效率 |
---|---|---|
順序存儲 | 高,可直接根據索引查找 | 低,插入刪除操作都有可能需要移動大量的數據 |
鏈式存儲 | 低,需要從頭開始查找 | 高 |
MessageQueue 主要涉及兩個方法:①boolean enqueueMessage(Message msg, long when),這個方法就是將消息插入消息隊列中;②Message 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方法就會阻塞在這裏,如果有新的消息到來時,next方法就會返回這個消息並在單鏈表中將其刪除。要退出這個無限循環可以調Loopper的quit()或者Looper的quitSafely(),前者是直接退出,後者是處理完現有消息再退出。對應next方法中的
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
這段代碼
3、Looper
Looper在Android消息機制中扮演消息循環的角色,具體來說就是不停的從MessageQueue中查看是否有新的消息,如果有新的消息則立即處理,否則一則阻塞在那裏。
我們知道Handler的工作需要Looper,比如:
new Thread("Thread#3"){
@Override
public void run() {
handler = new Handler();
}
}.start();
其中的handler是Activity的一個成員屬性,子線程默認是沒有Looper的,這樣就會報如下異常
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
沒有Looper那就自己創建,異常信息也告訴我們調Looper.prepare() 就可以,好吧,那我們就改一下
new Thread("Thread#3"){
@Override
public void run() {
Looper.prepare();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d(TAG, "handleMessage: 收到主線程發過來的消息啦 " + msg.what);
}
};
}
}.start();
這個時候我們在Activity增加一個Button去點擊發送消息到這個子線程中的handler
public void sendMessage(View view) {
int what = 0;
handler.sendEmptyMessage(what);
}
結果是根本不會執行handleMessage(Message msg)方法,原因是我們沒有調用Looper.loop()方法來開啓消息循環,也就是消息發出去了,但是Looper並沒有去取消息。將代碼改爲如下即可:
new Thread("Thread#3"){
@Override
public void run() {
Looper.prepare();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d(TAG, "handleMessage: 收到主線程發過來的消息啦 " + msg.what);
}
};
Looper.loop();
}
}.start();
爲什麼這個要增加一個點擊事件來發消息而不是直接發送,主要是這個handler在子線程中創建,不知道什麼時候它會執行完,所以我是等一會再點發送。如果調用handler.getLooper().quit()或者handler.getLooper().quitSafely(),這個線程就會終止,所以不能再發消息到這個handler否則會報如下異常:
Looper.loop()方法也是個無限循環,只有MessageQueue的next方法返回null的時候才退出,也就是調用Looper的quit方法或者quitSafely()方法時,MessageQueue的next方法會返回null,這個時候消息循環就終止了。
4、Handler
Handler的主要工作是發送消息和接收消息,消息發送可以通過post的一系列方法以及send的一系列方法來實現,post的一系列方法的最終是通過send的一系列方法實現的。發一條消息的典型過程如下:
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發送消息,僅僅是往消息隊列中插入一條消息,MessageQueue的next方法會返回這個消息給Looper,Looper收到消息後就開始處理了,最終由Looper交由Handler處理,即Handler的dispathMessage方法被調用,這時Handler就進入了消息處理階段,dispathMessage方法的實現如下:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
①首先檢查 msg.callback對象,這是個 Runnable對象,即通過post方法所傳遞地參數,如果這個參數不爲null,則調用這個參數的run方法(handleCallback(msg)這個調用就是調了Runable的run方法)。示例:
mHandler.post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "msg.callback != null ");
}
});
②其次檢查mCallback是否爲空,不爲空則調mCallback的handleMessage(msg)方法,這個mCallback是一個接口
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
public interface Callback {
public boolean handleMessage(Message msg);
}
示例:
private Handler handler = new Handler(new Handler.Callback(){
@Override
public boolean handleMessage(Message msg) {
Log.d(TAG, "mCallback != null ");
return true;
}
});
handler.sendEmptyMessage(0);
- 創建Handler的幾種方式:(其中①②都是屬於派生子類,常用②③的方式)
①派生子類
private MyHandler myHandler = new MyHandler();
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
}
②匿名內部類
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
③使用callback接口
private Handler handler = new Handler(new Handler.Callback(){
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
- 另外Handler還有一個比較特殊的構造方法:
/**
* Use the provided {@link Looper} instead of the default one.
*
* @param looper The looper, must not be null.
*/
public Handler(Looper looper) {
this(looper, null, false);
}
這個構造方法可以指定Looper,我們知道,Looper是跟線程綁定的,換句話說就是Handler可以工作在任意一個線程,也就是不一定是主線程,當不在主線程時就不能用來更新UI。例子:(這樣寫就是使用子線程的Looper)
new Thread("Thread#4"){
@Override
public void run() {
Looper.prepare();
handlerInThread = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
textView.setText("子線程Handler更新UI");
}
};
Looper.loop();
}
}.start();
我們可以使用public Handler(Looper looper) 這個構造方法來指定Handler的Looper
new Thread("Thread#4"){
@Override
public void run() {
Looper.prepare();
handlerInThread = new Handler(getMainLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//雖然這個Handler在子線程中創建,但其Looper是主線程的Looper,也就是這個方法是在主線程中執行的,當然可以更新UI
textView.setText("子線程Handler更新UI");
}
};
Looper.loop();
}
}.start();
這樣寫也就意味着這個Handler是工作在主線程的,當然可以更新UI。所以,如果你的Handler是用來更新UI的,那麼推薦使用new Handler(getMainLooper())這種方式來實現,不管你在哪裏new這個對象,都可以用來更新UI,有時候這樣可以減少不必要的麻煩。典型的例子是,我們在使用AsynTask時,必須在主線程去做類似這樣的操作new MyAsycTask().execute();原因是在AsynTask內部會創建一個Handler,更新UI相關的操作都會藉助這個Handler來切換回主線程,所以必須保證Handler的Looper是UI線程的。當然在較高的Android版本已經沒有這個限制了。主要原因請看下面的源碼:
在AsycTask內部有一個 private static InternalHandler sHandler; ,我們看一下InternalHandler的實現。
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
可以看到,創建這個sHandler的時候已經使用new Handler(getMainLooper())這種方式將主線程的Looper傳進去,不管你在哪個線程創建,最終都會切換回到主線程去執行handleMessage方法。Android-22及更高版本是可以在子線程中new MyAsycTask().execute();的,Android-21版本及以下的應該都不可以。Android-21的InternalHandler如下:
private static class InternalHandler extends Handler {
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult result = (AsyncTaskResult) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
這個版本的源碼使用的是默認的Handler的構造方法,也就是Looper是創建它的線程,所以要求在主線程中創建。
- 以上源碼大部分來自 Android-24.