Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 開發實踐:打造自帶消息迴圈(Looper)的工作執行緒

上一篇提到 Android 的 UI 執行緒是一種帶消息迴圈(Looper)的執行緒,而 Android 也封裝了 HandlerThread 這樣的類別:它可以綁定 Handler,用 sendMessage() 送訊息進去,再由 handleMessage() 處理。說法有點抽象,本文就用最原始的 Java 類庫手刻一個帶 Looper 的執行緒,順著實作把原理看明白。

1. 先搭一個可用的執行緒骨架

public class LooperThread {

  private volatile boolean mIsLooperQuit = false;

  private Thread mThread;

  public void start() {
    if (mThread != null) {
      return;
    }
    mIsLooperQuit = false;
    mThread = new Thread(mLooperRunnable);
    mThread.start();
  }

  public void stop() {
    if (mThread == null) {
      return;
    }
    mIsLooperQuit = true;
    mThread = null;
  }

  protected Runnable mLooperRunnable = new Runnable() {
    @Override
    public void run() {
      while (!mIsLooperQuit) {
      }
    }
  };
}

mLooperRunnable.run() 是迴圈主體,mIsLooperQuit 是離開迴圈的條件。但這個迴圈會空轉燒 CPU,所以下一步要讓它在沒事可做時睡著。

2. 加入訊息的傳送與處理

(1)定義訊息結構與佇列:

public class LooperThread {

  private Queue<Message> mMessageQueue = new LinkedList<Message>();

  public static class Message {
    int what;
  }
}

(2)建立互斥鎖與條件變數:

private Lock mLock = new ReentrantLock();
private Condition mCondition = mLock.newCondition();

(3)對外提供的送訊息介面:

// 由外部模組呼叫,把訊息投遞給執行緒
public void sendMessage(Message message) {
  if (mThread == null) {
    return;
  }
  mLock.lock();
  mMessageQueue.add(message);
  mCondition.signal();   // 通知迴圈:有訊息,快來處理
  mLock.unlock();
}

(4)執行緒內部的處理函式:

// 由執行緒內部呼叫
public void handleMessage(Message message) {
  // 實務上可透過 Callback 回呼監聽者
}

(5)在迴圈中取用訊息:

protected Runnable mLooperRunnable = new Runnable() {
  @Override
  public void run() {
    while (!mIsLooperQuit) {

      mLock.lock();
      Message message = null;
      try {
        while (!mIsLooperQuit && mMessageQueue.isEmpty()) {
          mCondition.await();     // 沒有訊息就休眠,不空轉
        }
        message = mMessageQueue.poll();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        mLock.unlock();
      }

      handleMessage(message);
    }
  }
};

(6)修改 stop(),把休眠中的迴圈叫醒:

public void stop() {
  if (mThread == null) {
    return;
  }

  mIsLooperQuit = true;

  mLock.lock();
  mCondition.signal();
  mLock.unlock();

  mMessageQueue.clear();
  mThread = null;
}

少了 signal() 這一步,stop() 會在佇列為空時永遠喚不醒執行緒,這是自刻 Looper 最常見的 bug。

3. 這套設計對應了什麼

把上面的元件逐一對照 Android 的原始碼,你會發現結構幾乎一一相符:mMessageQueue 對應 MessageQueue,迴圈對應 Looper.loop(),handleMessage() 對應 Handler 的分派,而 mLock/mCondition 的角色則由 MessageQueue 內部的 native 同步機制(以及 epoll 等待)擔任。差别只在正式實作還要處理 Barrier、同步屏障、IdleHandler、訊息回收與超時(sendMessageDelayed)等細節。

理解這一層之後,再看 HandlerThread 就只是「幫你把 Thread + Looper.prepare() + Looper.loop() 包好」而已;而它之所以適合做序列化的背景工作(例如逐筆處理資料庫寫入),正是因為所有訊息都在同一條執行緒上順序執行,天然免除了資料競爭。

Copyright © Linux教程網 All Rights Reserved