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

Android 子執行緒隨時切換主執行緒的封裝實作

編輯:關於 Android 程式設計

問題背景

Android 開發繞不開耗時操作:網路請求、資料庫查詢、檔案讀寫。這些工作不能放在主線程,否則會卡住 UI 迴圈,最後引發 ANR。所以必須另開子線程,算完再回頭更新介面——而介面控制項只能在主線程操作。於是「從子線程切回主線程」成了每個 Android 開發者都要面對的課題。

既有方案與痛點

常見做法是 AsyncTask 或 Handler。AsyncTask 是官方封裝,寫起來簡單,但場合受限,用過幾次之後往往就不再使用。Handler 則近乎萬能,原理是訊息迴圈:在主線程建立 Handler 時就啟動迴圈,逐一消化訊息佇列中的任務。

問題在於麻煩。每次都要宣告一個 Handler 子類別,覆寫 handleMessage(Message msg),還得處理參數怎麼塞進 Message、怎麼從 Message 取出來。流程一長,样板程式碼就堆成山。

設計目標

既然如此,不如自己包一層。先把需求條列出來:

  • 底層仍用 Handler 做線程切換。
  • 子線程只要一行呼叫就能切到主線程做事。
  • 提供同步版本:子線程進入後先阻塞,等主線程做完再繼續(這個需求很重要,例如需要拿到 UI 操作後的結果才能往下走)。
  • 不能拖慢效率,主線程不能被單一任務長期佔用。
  • 主線程單次執行要有時間上限。

對應的實作決策:用 Handler 繼承實作;對外暴露靜態方法;用兩個佇列分別承載同步與非同步任務;用一個計時變數控制單次占用主線程的時間;參數則統一用 Runnable 傳入,最省事。

ToolKit:對外介面

public class ToolKit {

    private static HandlerPoster mainPoster = null;

    private static HandlerPoster getMainPoster() {
        if (mainPoster == null) {
            synchronized (ToolKit.class) {
                if (mainPoster == null) {
                    // 綁定主線程 Looper,單次最多占用 20 毫秒
                    mainPoster = new HandlerPoster(Looper.getMainLooper(), 20);
                }
            }
        }
        return mainPoster;
    }

    /** 非同步:不阻塞子線程 */
    public static void runOnMainThreadAsync(Runnable runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run();
            return;
        }
        getMainPoster().async(runnable);
    }

    /** 同步:阻塞子線程,等主線程做完才繼續 */
    public static void runOnMainThreadSync(Runnable runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run();
            return;
        }
        SyncPost poster = new SyncPost(runnable);
        getMainPoster().sync(poster);
        poster.waitRun();
    }

    public static void dispose() {
        if (mainPoster != null) {
            mainPoster.dispose();
            mainPoster = null;
        }
    }
}

兩個對外方法都先判斷呼叫者是不是主線程:如果本來就在主線程,直接執行就好,繞一圈佇列毫無意義。getMainPoster() 用雙重檢查鎖確保多線程同時呼叫也只會建立一個實例。

HandlerPoster:佇列與調度

final class HandlerPoster extends Handler {

    private final int ASYNC = 0x1;
    private final int SYNC  = 0x2;

    private final Queue<Runnable> asyncPool;
    private final Queue<SyncPost> syncPool;
    private final int maxMillisInsideHandleMessage;

    private boolean asyncActive;
    private boolean syncActive;

    HandlerPoster(Looper looper, int maxMillisInsideHandleMessage) {
        super(looper);
        this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
        asyncPool = new LinkedList<>();
        syncPool = new LinkedList<>();
    }

    void dispose() {
        this.removeCallbacksAndMessages(null);
        this.asyncPool.clear();
        this.syncPool.clear();
    }

    void async(Runnable runnable) {
        synchronized (asyncPool) {
            asyncPool.offer(runnable);
            if (!asyncActive) {
                asyncActive = true;
                if (!sendMessage(obtainMessage(ASYNC))) {
                    throw new RuntimeException("Could not send handler message");
                }
            }
        }
    }

    void sync(SyncPost post) {
        synchronized (syncPool) {
            syncPool.offer(post);
            if (!syncActive) {
                syncActive = true;
                if (!sendMessage(obtainMessage(SYNC))) {
                    throw new RuntimeException("Could not send handler message");
                }
            }
        }
    }

    @Override
    public void handleMessage(Message msg) {
        if (msg.what == ASYNC) {
            boolean rescheduled = false;
            try {
                long started = SystemClock.uptimeMillis();
                while (true) {
                    Runnable runnable = asyncPool.poll();
                    if (runnable == null) {
                        synchronized (asyncPool) {
                            // 同步塊內再確認一次,避免競態
                            runnable = asyncPool.poll();
                            if (runnable == null) {
                                asyncActive = false;
                                return;
                            }
                        }
                    }
                    runnable.run();
                    if (SystemClock.uptimeMillis() - started >= maxMillisInsideHandleMessage) {
                        // 超時就讓出主線程,稍後再排一次
                        if (!sendMessage(obtainMessage(ASYNC))) {
                            throw new RuntimeException("Could not send handler message");
                        }
                        rescheduled = true;
                        return;
                    }
                }
            } finally {
                asyncActive = rescheduled;
            }
        } else if (msg.what == SYNC) {
            boolean rescheduled = false;
            try {
                long started = SystemClock.uptimeMillis();
                while (true) {
                    SyncPost post = syncPool.poll();
                    if (post == null) {
                        synchronized (syncPool) {
                            post = syncPool.poll();
                            if (post == null) {
                                syncActive = false;
                                return;
                            }
                        }
                    }
                    post.run();
                    if (SystemClock.uptimeMillis() - started >= maxMillisInsideHandleMessage) {
                        if (!sendMessage(obtainMessage(SYNC))) {
                            throw new RuntimeException("Could not send handler message");
                        }
                        rescheduled = true;
                        return;
                    }
                }
            } finally {
                syncActive = rescheduled;
            }
        } else {
            super.handleMessage(msg);
        }
    }
}

幾個設計意圖值得說明:

兩個 active 旗標:避免佇列裡堆積大量重複的訊息。只有從「未執行」轉為「執行中」時才送一次訊息,後續任務直接進佇列排隊。

時間預扣:每跑完一個任務就檢查耗時,一旦超過 maxMillisInsideHandleMessage(這裡是 20 毫秒),無論佇列是否清空都立刻退出並重新排隊。這樣主線程不會被單一批次長期佔用,UI 仍有喘息空間。

obtainMessage():複用系統閒置的 Message 物件,減少不必要的配置。

二次 poll:第一次 poll 為空時進入同步塊再 poll 一次。若剛好有任務在這其間被塞進來,第二次就能取到,不必多跑一輪迴圈。

SyncPost:同步的關鍵

同步與非同步的處理流程幾乎一樣,差別全在這個包裝類:

final class SyncPost {

    boolean end = false;
    Runnable runnable;

    SyncPost(Runnable runnable) {
        this.runnable = runnable;
    }

    public void run() {
        synchronized (this) {
            runnable.run();
            end = true;
            this.notifyAll();
        }
    }

    public void waitRun() {
        if (!end) {
            synchronized (this) {
                if (!end) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

子線程呼叫 waitRun() 後便停在 wait(),直到主線程執行 run() 並 notifyAll(),子線程才被喚醒繼續往下。這裡的 end 旗標是為了處理一個常見競態:如果主線程在子線程走到 wait() 之前就已經跑完 run(),那麼 notifyAll() 會落空,子線程若無條件 wait() 就會永遠醒不來。先檢查 end,就能避開這個死等。

使用方式

// Runnable 的 run() 會在主線程執行,可在裡面操作介面
// 同步進入:子線程停下來等主線程做完
ToolKit.runOnMainThreadSync(new Runnable() {
    @Override public void run() { /* 更新 UI */ }
});

// 非同步進入:丟過去就不管了
ToolKit.runOnMainThreadAsync(new Runnable() {
    @Override public void run() { /* 更新 UI */ }
});

對外只有這兩個方法,共用的部分(HandlerPoster、SyncPost)都收在套件內部。這套封裝也收錄在 Genius-Android 這個開源專案裡。

要注意的是,同步版本有潛在死鎖風險:若在主線程誤用 runOnMainThreadSync,雖然程式碼已用 Looper 判斷擋掉,但若在持有某個鎖的情況下呼叫,仍可能出事。實務上建議同步版本只用於「確實需要拿到 UI 操作結果」的少數場景。

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