-
ThreadLocal
对象是一种特殊的全局变量,因为他的“全局”性只局限于自己所在的线程 - 当
Looper
创建时,消息队列也同时被创建出来
final MessageQueue mQueue;
private Looper(boolean quitAllowed){
mQueue = new MessageQueue(quitAllowed);
mRun = true;
mThread = Thread.currentThread();// Looper与当前线程建立对应关系
}
Handler
与Looper
,MessageQueue
建立联系
public Handler(){
/*省略部分代码*/
mLooper = Looper.myLooper();// 通过sThreadLocal.get()来获取当前线程中的Looper实例
mQueue = mLooper.mQueue;// mQueue是Looper与Handler之间沟通的桥梁
mCallback = callback;
}
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}