Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 異步消息處理機制源碼解析:Looper、MessageQueue、Message 與 Handler

編輯:關於 Android 程式設計

四者的關係

  • Looper:線程的消息循環處理器,每個線程最多一個。內部持有一個 MessageQueue,該線程的所有消息按時間排序存放在其中。系統在應用啟動時為主線程創建了 Looper,自定義線程則需手動調用 Looper.prepare()。
  • Handler:Message 的發送者與處理者。構造時與一個 Looper 關聯。Handler 與 Looper 是多對一的關係——多個 Handler 可以共用同一個 Looper,反之不行。
  • Message:消息載體,Parcelable 的派生類,包含 what、arg1、arg2、obj 等字段。
  • MessageQueue:按時間排序的消息單鏈表,由 Looper 持有。

主要成員速查

Looper

public final class Looper {
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;
    final MessageQueue mQueue;
    final Thread mThread;

    public static void prepare() { ... }
    private static void prepare(boolean quitAllowed) { ... }
    public static void prepareMainLooper() { ... }
    public static Looper getMainLooper() { ... }
    public static Looper myLooper() { ... }
    public static void loop() { ... }
}

MessageQueue

public final class MessageQueue {
    Message next() { ... }
    boolean enqueueMessage(Message msg, long when) { ... }
}

Message

public final class Message implements Parcelable {
    public int what;
    public int arg1;
    public int arg2;
    public Object obj;
    public Messenger replyTo;

    private static Message sPool;        // 消息池鏈表頭
    private static int sPoolSize = 0;
    private static final int MAX_POOL_SIZE = 50;

    public static Message obtain() { ... }
    public void sendToTarget() { ... }
    void recycleUnchecked() { ... }
}

問答解析

1. ThreadLocal 的作用

ThreadLocal 即「線程本地變量」。把數據放進 ThreadLocal 後,每個線程都會持有該變量的一份獨立副本,從根本上避免並發訪問的線程安全問題。Looper 正是用它來保證「每個線程各自持有自己的 Looper 實例」。

2. 為什麼主線程不需要 Looper.prepare()

因為 ActivityThread.main() 已經調用了 Looper.prepareMainLooper():

public static void main(String[] args) {
    Looper.prepareMainLooper();
    ActivityThread thread = new ActivityThread();
    thread.attach(false);
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

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

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));
}

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

從這段代碼可以得出兩個結論:一個線程只能有一個 Looper 對象;同一線程中 prepare() 系列方法最多調用一次,重複調用會拋異常。子線程調用的 Looper.prepare() 內部也是 prepare(true)。

3. 實例化 Handler 時系統做了什麼

public Handler(Callback callback, boolean async) {
    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;
}

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

構造器做了三件事:取得當前線程的 Looper(取不到就拋異常,這正是「必須先 prepare」的原因)、關聯該 Looper 的 MessageQueue、保存 Callback 與 async 標誌。

dispatchMessage 揭示了消息的三條處理路徑:優先執行 Message 自帶的 Runnable(callback 字段);其次執行構造時傳入的 Callback 接口;最後才是我們最熟悉的 handleMessage()。

4. 為什麼要調用 Looper.loop()

public static void loop() {
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException(
            "No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;

    for (;;) {
        Message msg = queue.next();     // 沒有消息時阻塞在這裡
        if (msg == null) {
            return;                     // 隊列退出,循環結束
        }
        msg.target.dispatchMessage(msg);
        msg.recycleUnchecked();         // 處理完後回收進消息池
    }
}

loop() 是一個死循環,不斷從隊列取消息。關鍵在 msg.target.dispatchMessage(msg)——target 就是發送該消息的 Handler,因此消息由哪個 Handler 發出,就由哪個 Handler 處理。Message.sendToTarget() 的本質也是 target.sendMessage(this)。

5. sendMessage 如何入隊,隊列如何組織

各個 send 變體最終都彙集到 enqueueMessage:

boolean enqueueMessage(Message msg, long when) {
    synchronized (this) {
        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;

        if (p == null || when == 0 || when < p.when) {
            // 時間最小,直接插入頭部
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // 否則遍歷找到合適位置插入
            Message prev;
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            msg.next = p;
            prev.next = msg;
        }
    }
    return true;
}

MessageQueue 本質是一個按 when 字段升序排列的單鏈表,mMessages 為頭節點。插入時先判斷是否比頭節點更早,若是則直接頭插;否則遍歷找到第一個比自己晚的節點插入。延遲消息正是依靠 when = now + delayMillis 來實現的。

6. 線程之間是如何切換的

在 A 線程創建 Handler 並調用 loop() 進入循環等待;B 線程通過該 Handler 的 sendMessage() 把消息放入 A 線程的 MessageQueue;A 線程的 loop 循環取到消息並調用 dispatchMessage——此時的執行線程就是 A。線程切換由此完成。

7. 創建消息的三種方式

public static Message obtain() {
    synchronized (sPoolSync) {
        if (sPool != null) {
            Message m = sPool;
            sPool = m.next;
            m.next = null;
            m.flags = 0;
            sPoolSize--;
            return m;
        }
    }
    return new Message();
}

void recycleUnchecked() {
    synchronized (sPoolSync) {
        if (sPoolSize < MAX_POOL_SIZE) {
            next = sPool;
            sPool = this;
            sPoolSize++;
        }
    }
}

消息池是一個上限 50 的單鏈表。處理完的消息通過頭插法放回池中,下次 obtain() 直接複用,避免頻繁創建對象帶來的 GC 壓力。因此推薦使用 obtain() 而非 new Message()。

8. post 方法是幹什麼的

private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

private static void handleCallback(Message message) {
    message.callback.run();
}

post 系列內部同樣調用 send,只是先把 Runnable 塞進 Message 的 callback 字段。分發時走 handleCallback 分支,直接調用 run()——注意這並不會創建新線程,而是在當前(即 Looper 所屬)線程中同步執行。

post 與 send 的區別:post 發送的是自帶處理邏輯(Runnable)的消息,在 handleCallback 中執行;send 發送的是裸消息,只能在 handleMessage 中處理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved