在主线程中不同的Handler会使用相同的MessageQueue吗?

935 阅读1分钟

分析这个问题需要对MessagQueue的创建有一定了解,查看Looper里面的源代码,MessageQueue的创建的代码如下

  private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

这是Looper里面唯一的会对messageQueue进行创建的方法,调用这个方法只有一个,就是perpare(boolean quitAllowed)

  private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

通过RuntimeException的错误可以直接得出结论每一个线程只能有一个Looper也只会有一个MessageQueue。也就是说Handler和Looer,Message是多对一的关系。当然如果要深入研究的话可以继续看源码,源码调用perpare(boolean quitAllowed)有两个地方,一个是我们在子线程创建Handler的perpare()

 public static void prepare() {
        prepare(true);
    }

另一个调用的地方是prepareMainLooper(),此方法在ActivityThread.class和SystemServer.class的main方法调用。

 public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }