Android消息機制
- Android消息機制主要指Handle的運行機制
- MessageQueue和Looper支撐Handle運行
- MessageQueue是單鏈表結(jié)構(gòu)
- Looper無線循環(huán)查找消息隊列是否有新消息缓升,如果有則處理倦春,否者一直等待
- Handle創(chuàng)建在哪個線程就會使用當前那個線程的Looper辆它,由FrameWork源碼可知。
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;
}
Handle 持有Looper和MessageQueue引用
Looper 持有MessageQueue和ThreadLocal,Thread引用
-
ThreadLocal
為每個線程提供一個變量的獨立的變量副本,所以每個線程只會獨立的改變自己的副本剧腻,而不會影響其他對應(yīng)的副本侦高。
如何實現(xiàn)變量的副本的
實現(xiàn)很簡單
ThreadLocal內(nèi)部維護一個Map,用于存儲每一個線程變量副本胖眷,Map中的鍵為線程對象武通,值就是對應(yīng)線程的變量副本。
解決多線程并發(fā)問題