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

Android 線程池入門:從 Callable、FutureTask 到 ThreadPoolExecutor 源碼追蹤

編輯:關於 Android 程式設計

一直想認真寫一篇 AsyncTask 的原理解析。AsyncTask 的底層由兩塊拼成:線程池與訊息機制。訊息機制我先前已經寫過,有興趣的可以先看那篇。這篇專心把 Android 線程池這條線拉直,內容分成兩部分——本篇是基礎篇,下一篇再往深處走。

正式進入線程池之前,得先認識兩個配角:Callable 與 FutureTask。它們不只出現在線程池裡,AsyncTask 的實作也大量用到。

Callable 與 FutureTask

Callable 是一個泛型介面,接受型別參數 V,內部只有一個回傳 V 的 call() 方法:

public interface Callable<V> {
    V call() throws Exception;
}

我們對 Runnable 比較熟悉。兩者結構相似,差別在於:call() 有回傳值,run() 沒有;Runnable 通常被包進 Thread 裡,而 Callable 則被包進 FutureTask 裡。

那就來看 FutureTask。先從繼承結構切入:

public class FutureTask<V> implements RunnableFuture<V> {
    // 其餘程式碼省略
}

它實作的是 RunnableFuture,而這個名字怎麼看都像 Runnable 與 Future 的合體。逐一確認:

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * 若任務未被取消,則將運算結果設定到此 Future
     */
    void run();
}

確實如此,RunnableFuture 同時繼承了 Runnable 與 Future。

那 Future 又是什麼?官方文件的說法是:Future 代表一個非同步運算的結果。而書籍裡的定義更貼近實務——Future 為線程池提供了一套可管理的任務標準,讓你能取消任務、查詢是否完成、取得結果、設定結果:

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException;
}

FutureTask 同時實作了這兩個介面,於是兩邊的能力都到手了。最直觀的好處就是:任務跑完之後,你可以把結果拿回來。接著往內部挖。

從建構子看包裝過程

public FutureTask(Callable<V> callable) {
    if (callable == null) throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;  // 確保 callable 的可見性
}

這個建構子直接接收一個 Callable,完成包裝。

第二個建構子則接收 Runnable:

public FutureTask(Runnable runnable, V result) {
    this.callable = Executors.callable(runnable, result);
    this.state = NEW;
}

關鍵是 Executors.callable(),它把 Runnable 轉成 Callable 再存進欄位。順帶一提,Android 中建立線程池走的是「靜態工廠方法」模式,而這個工廠正是 Executors,後面會再回來。先看 callable() 內部:

public static <T> Callable<T> callable(Runnable task, T result) {
    if (task == null) throw new NullPointerException();
    return new RunnableAdapter<T>(task, result);
}

傳入的 Runnable 為 null 就拋空指標異常,否則包成 RunnableAdapter——這是 Executors 的內部類,實作了 Callable:

static final class RunnableAdapter<T> implements Callable<T> {
    final Runnable task;
    final T result;

    RunnableAdapter(Runnable task, T result) {
        this.task = task;
        this.result = result;
    }

    public T call() {
        task.run();
        return result;
    }
}

這裡用的是轉接器模式(Adapter):建構時收進 Runnable,而呼叫 call() 時,實際跑的其實是 run()。對呼叫方而言,他看到的就是一個 Callable,內部的轉接細節被完全隱藏。

小結一下:無論你注入的是 Runnable 還是 Callable,FutureTask 最終執行的都是 Callable 的任務——傳入 Runnable 時會先被 Executors.callable() 轉一遍。建構子看起來繁複,其實只是把初始化與型別統一的事情做乾淨。

run() 方法如何驅動 call()

既然 FutureTask 是 Runnable 的實作,它勢必得實作 run():

public void run() {
    if (state != NEW ||
            !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
        return;
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
                result = c.call();
                ran = true;
            } catch (Throwable ex) {
                result = null;
                ran = false;
                setException(ex);
            }
            if (ran) set(result);
        }
    } finally {
        // runner 必須在狀態底定前保持非 null,以避免 run() 被併發呼叫
        runner = null;
        // 清空 runner 後要重新讀取 state,避免中斷訊號外洩
        int s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}

只要 FutureTask 是正常建立的,c != null && state == NEW 這個判斷就會通過。也就是說:run() 一旦被呼叫,call() 必然被執行,其回傳值會存進區域變數 result(型別在建構 FutureTask 的當下就已確定),最後透過 set() 寫入內部狀態。因此我們能用 get() 把結果取出——準確地說,取出的是 call() 的執行結果。這正是 FutureTask 設計上的巧妙之處:把「執行」與「取回結果」這兩件事拆開,讓非同步變得可操作。

線程池:從建立到執行

本篇作為基礎篇,先建立整體輪廓,細節留到下一篇。用靜態工廠方法建立一個最簡單的線程池:

ExecutorService executorService = Executors.newSingleThreadExecutor();

接著把 FutureTask 丟進去:

executorService.submit(new FutureTask<Integer>(new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
        // 具體邏輯
        return null;
    }
}));

用帶 Callable 的建構子做出 FutureTask,傳進 submit() 送出。submit() 會回傳一個 Future,你就能靠它取得 call() 的結果。

那麼,submit() 之後究竟發生了什麼?我們已知 Callable 被包在 FutureTask 裡,而 call() 是在 FutureTask.run() 中被呼叫的——問題只剩一個:run() 在哪裡被觸發?

newSingleThreadExecutor:真正的核心是 ThreadPoolExecutor

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService(
            new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>()));
}

ExecutorService 只是介面,真正幹活的是 ThreadPoolExecutor,它才是整個體系的核心。但 ThreadPoolExecutor 裡找不到 submit(),只能往父類找。它繼承自抽象類 AbstractExecutorService,submit() 就在那裡:

public Future<?> submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<Void> ftask = newTaskFor(task, null);
    execute(ftask);
    return ftask;
}

繼續看 newTaskFor():

protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
    return new FutureTask<T>(runnable, value);
}

內部呼叫的就是剛才那個 FutureTask 建構子。這一步的意義是:保證最終傳進 execute() 的一定是 RunnableFuture。

而 AbstractExecutorService 並未實作 execute()——合理,這件事本該交給子類。回到 ThreadPoolExecutor:

public void execute(Runnable command) {
    if (command == null) throw new NullPointerException();
    /*
     * 分三個階段處理:
     * 1. 若執行中的執行緒數少於 corePoolSize,嘗試開新執行緒,並以 command 作為第一個任務。
     *    addWorker 會以原子方式檢查 runState 與 workerCount,避免誤判而多開執行緒。
     * 2. 若任務成功入列,仍要再確認一次是否需要補上執行緒(因為期間可能有執行緒死亡),
     *    或線程池已在進入此方法後關閉。必要時要回滾入列,或補一條新執行緒。
     * 3. 若無法入列,則嘗試直接開新執行緒;若失敗,代表已關閉或已飽和,此時拒絕任務。
     */
    int c = ctl.get();
    if (workerCountOf(c) < corePoolSize) {
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        if (! isRunning(recheck) && remove(command))
            reject(command);
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    else if (!addWorker(command, false))
        reject(command);
}

回顧一下:在 submit() 中傳進 execute() 的是 RunnableFuture。這裡做了一系列判斷,圍繞核心執行緒數與任務佇列展開(下一篇會細講)。RunnableFuture 最後被交給 addWorker(),我們直接看那個方法:

private boolean addWorker(Runnable firstTask, boolean core) {
    retry: for (;;) {
        // 程式碼省略
        Worker w = null;
        try {
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    // 持鎖後再次檢查狀態,
                    // 若在取得鎖之前 ThreadFactory 失敗或線程池已關閉,則放棄
                    int rs = runStateOf(ctl.get());
                    if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // 先確認 t 可被啟動
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }
}

抓重點,傳進來的 Runnable 在這裡被使用:

w = new Worker(firstTask);
final Thread t = w.thread;

Worker 又把它包了一層。其建構子如下:

Worker(Runnable firstTask) {
    setState(-1); // 在 runWorker 之前先阻斷中斷
    this.firstTask = firstTask;
    this.thread = getThreadFactory().newThread(this);
}

接著取出 Worker 內部的執行緒賦給 t,經過一連串狀態檢查後:

if (workerAdded) {
    t.start();
    workerStarted = true;
}

執行緒啟動,Worker.run() 隨之被呼叫:

/** 將主執行迴圈委派給外層的 runWorker */
public void run() {
    runWorker(this);
}

而 runWorker() 是這樣的:

final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    Runnable task = w.firstTask;
    w.firstTask = null;
    w.unlock(); // 允許中斷
    boolean completedAbruptly = true;
    try {
        while (task != null || (task = getTask()) != null) {
            w.lock();
            // 若線程池正在停止,確保執行緒被中斷;
            // 否則確保它沒有被中斷。第二種情況需要再次檢查,
            // 以處理 shutdownNow 與清除中斷狀態之間的競態
            if ((runStateAtLeast(ctl.get(), STOP) ||
                    (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP)))
                    && !wt.isInterrupted())
                wt.interrupt();
            try {
                beforeExecute(wt, task);
                Throwable thrown = null;
                try {
                    task.run();
                } catch (RuntimeException x) {
                    thrown = x; throw x;
                } catch (Error x) {
                    thrown = x; throw x;
                } catch (Throwable x) {
                    thrown = x; throw new Error(x);
                } finally {
                    afterExecute(task, thrown);
                }
            } finally {
                task = null;
                w.completedTasks++;
                w.unlock();
            }
        }
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);
    }
}

看這一行:

Runnable task = w.firstTask;

它取出了 Worker 先前包裝的 Runnable(也就是最初那個 FutureTask)並賦給 task。再往下:

try {
    beforeExecute(wt, task);
    Throwable thrown = null;
    try {
        task.run();
    } catch (RuntimeException x) {
        thrown = x; throw x;
    } catch (Error x) {
        thrown = x; throw x;
    } catch (Throwable x) {
        thrown = x; throw new Error(x);
    } finally {
        afterExecute(task, thrown);
    }
}

task.run() 終於被呼叫了。這就是我們一路追問的答案:submit() 送出的 FutureTask,其 run() 是在 runWorker() 的工作迴圈裡被執行的,而 run() 內部又驅動了 call()。

把整條鏈路串起來:submit() → newTaskFor() 包裝成 FutureTask → execute() 決定開執行緒或入列 → addWorker() 建立 Worker 並啟動其執行緒 → runWorker() 取出任務並呼叫 run() → FutureTask.run() 呼叫 call() 並保存結果。

一路追下來不敢說思路百分之百清晰,但至少整體骨架已經在腦中成形。下一篇要談的核心執行緒數、任務佇列、拒絕策略與執行緒回收,會在這個骨架上把細節填滿。

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