第一次接觸 Android 的 Java 層應用開發,很多人會卡在同一个問題上:畫面明明只有一條主線程在跑,為什麼點擊事件、按鍵、計時器、非同步回呼都能被排隊處理,而且彼此不會互相踩踏?早期 Google 只開放了 Java 層的 API,底層細節藏得很深,光憑感覺很難回答。
其實從原理上推,答案並不複雜:系統裡有一個消息佇列(Message Queue),還有一個不停轉動的消息迴圈(Message Loop)。主線程就守在那個迴圈裡,一次又一次把消息取出、分派、處理完再取下一個。Android 用 Looper 把「迴圈 + 佇列」這兩件事包成一個類,再用 Handler 作為對外的投遞入口——你想讓某段程式碼在主線程執行,就把消息塞進 Looper 的佇列,剩下的交給迴圈。若拿 Windows 視窗程式設計來類比,Handler 的角色有點像 SendMessage 時用到的視窗句柄:它標明了「這條消息該由誰來收」。
先看這個類的欄位,骨架其實很樸素:
public final class Looper {
// 是否印出除錯資訊
private static final boolean DEBUG = false;
// 線程本地儲存(Thread Local Storage)的封裝
private static final ThreadLocal sThreadLocal = new ThreadLocal();
final MessageQueue mQueue; // 消息佇列
volatile boolean mRun; // 迴圈是否仍在運行
Thread mThread; // 與此 Looper 關聯的線程
Printer mLogging = null; // 除錯輸出對象
private static Looper mMainLooper = null; // 應用主線程的 Looper
}
變數的存放位置一般只有兩種:要麼在堆疊上,例如函式內定義的區域變數;要麼在堆上,例如 new 或 malloc 出來的物件。但 Linux、Windows 這類系統都提供了「線程本地儲存空間」:這塊空間與線程綁定,每條線程各自擁有一份。把和線程相關的狀態放進 TLS,就不必丟到堆上再靠鎖去同步,取用時也天然隔離。Android 正是用 sThreadLocal 來保存「當前線程對應哪個 Looper」,這也解釋了一個硬性規則:一條線程只能有一個 Looper。
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
如果同一條線程重複呼叫,就會直接拋出 RuntimeException。應用主線程的 Looper 由框架建立,開發者通常不需要自己動手,框架呼叫的是 prepareMainLooper():
public static final void prepareMainLooper() {
prepare();
setMainLooper(myLooper());
// 主消息迴圈不允許主動退出
if (Process.supportsProcesses()) {
myLooper().mQueue.mQuitAllowed = false;
}
}
也就是說,UI 線程的迴圈一旦啟動,就不會因為 quit() 而結束,它會陪著應用一路跑到進程消亡。
public static final void loop() {
Looper me = myLooper(); // 取出當前線程的 Looper
MessageQueue queue = me.mQueue; // 取出它的消息佇列
while (true) {
Message msg = queue.next(); // 取下一條待處理消息,沒有消息時會阻塞
if (msg != null) {
if (msg.target == null) {
return; // target 為 null 是退出消息的暗號
}
msg.target.dispatchMessage(msg); // 交給 Handler 分派
msg.recycle(); // 回收,消息物件回到池中重用
}
}
}
幾個值得留意的細節:靜態方法意味著它屬於「當前線程」而非某個實例;queue.next() 在佇列空閒時會阻塞,所以主線程不會空轉燒 CPU;msg.target 就是投遞這條消息的 Handler,分派動作由它接手;而 target 為 null 的消息是框架約定好的結束記號。
相對地,主線程想收工,就得靠 quit() 塞進這一條特殊消息:
public void quit() {
Message msg = Message.obtain();
// 直接入列,讓 target 保持 null,這就是退出消息的標記
mQueue.enqueueMessage(msg, 0);
}
myLooper() 從 TLS 取出當前線程的 Looper,myQueue() 再往下一層拿到佇列;setMessageLogging(Printer) 會在每條消息分派前後印出目標 Handler 與內容,是排查「消息到底卡在哪」的利器;私有建構子建立 Looper 時順手 new MessageQueue()、把 mRun 設為 true、記下 Thread.currentThread();dump() 則把佇列裡所有待處理消息逐條印出,方便確認積壓情況。
把這些拼起來,Android 的 UI 模型就清楚了:Looper 提供迴圈與佇列,Handler 負責投遞與接收。子線程若也想擁有這套能力,只要自己 Looper.prepare() 再 Looper.loop(),就得到一條安靜等待任務的「工作線程」——這正是 HandlerThread 背後的思路。