之前在讲Handler原理点我的时候,最后做了一个总结,一个现在只有一个Handler,Looper…,如下图:
但是一直没有搞清楚为什么?Why?
最近偶然翻源码,终于是找到了原因:
全局静态的变量sThreadLocal 用来保存Looper对象(就相当于一个Map集合,键位当前的Thead线程,值为Looper对象)
public final class Looper {
65 private static final String TAG = "Looper";
66
67 // sThreadLocal.get() will return null unless you've called prepare().
68 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
69 private static Looper sMainLooper; // guarded by Looper.class
71 final MessageQueue mQueue;
72 final Thread mThread;
73
74 private Printer mLogging;
75
再看Looper创建的地方:
public static void prepare() {
83 prepare(true);
84 }
85
86 private static void prepare(boolean quitAllowed) {
// 这里是关键,如果这个线程已经存在Looper报异常
87 if (sThreadLocal.get() != null) {
88 throw new RuntimeException("Only one Looper may be created per thread");
89 }
// 不存在,创建一个Looper设置到sThreadLocal
90 sThreadLocal.set(new Looper(quitAllowed));
91 }
从Looper的创建的地方,我们知道一个线程只有一个Looper,那MessageQueue,Handler只有一个也就不奇怪了。
ps:在子线程new Handler,如下:
33 * <p>This is a typical example of the implementation of a Looper thread,
34 * using the separation of {@link #prepare} and {@link #loop} to create an
35 * initial Handler to communicate with the Looper.
36 *
37 * <pre>
38 * class LooperThread extends Thread {
39 * public Handler mHandler;
40 *
41 * public void run() {
42 * Looper.prepare();
43 *
44 * mHandler = new Handler() {
45 * public void handleMessage(Message msg) {
46 * // process incoming messages here
47 * }
48 * };
49 *
50 * Looper.loop();
51 * }
52 * }</pre>
总结
多看源码,知识的源头是不尽的财富!