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

AsyncTask 源碼探究:execute 之後到底發生了什麼

編輯:關於 Android 開發

用得很熟,卻沒想過它怎麼運作

AsyncTask 天天在用,但它內部的原理一直沒有特意研究。今天趁著有時間,把它的運行機制記錄下來。

具體用法就不再贅述,先寫一個最基本的子類:

class MyAsyncTask extends AsyncTask<String, Integer, Boolean> {
    @Override
    protected Boolean doInBackground(String... voids) {
        return true;
    }
}

啟動方式大家也都知道:

new MyAsyncTask().execute("參數");

平時寫到這裡我們就不再深究了,因為任務已經跑起來。但仔細想想,有幾個問題值得追問:

  • 為什麼呼叫 execute() 就能運行?
  • 為什麼 doInBackground() 裡不能操作 UI,而 onPostExecute() 就可以?

接下來就一步一步看它內部到底做了哪些事。

第一步:建構式裡藏了兩個關鍵物件

public AsyncTask() {
    mWorker = new WorkerRunnable<Params, Result>() {
        public Result call() throws Exception {
            mTaskInvoked.set(true);
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            //noinspection unchecked
            Result result = doInBackground(mParams);
            Binder.flushPendingCommands();
            return postResult(result);
        }
    };

    mFuture = new FutureTask<Result>(mWorker) {
        @Override
        protected void done() {
            try {
                postResultIfNotInvoked(get());
            } catch (InterruptedException e) {
                android.util.Log.w(LOG_TAG, e);
            } catch (ExecutionException e) {
                throw new RuntimeException("An error occurred while executing doInBackground()",
                        e.getCause());
            } catch (CancellationException e) {
                postResultIfNotInvoked(null);
            }
        }
    };
}

看著程式碼不少,其實就是 new 了兩個物件:mWorker 與 mFuture,它們分別是 Callable 與 Future 的實作。值得注意的是,在實例化 mFuture 時,把 mWorker 當作參數傳了進去——這是兩者能串起來的關鍵。

第二步:execute 的走向

@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
    return executeOnExecutor(sDefaultExecutor, params);
}

@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) {
    if (mStatus != Status.PENDING) {
        switch (mStatus) {
            case RUNNING:
                throw new IllegalStateException("Cannot execute task:"
                        + " the task is already running.");
            case FINISHED:
                throw new IllegalStateException("Cannot execute task:"
                        + " the task has already been executed "
                        + "(a task can be executed only once)");
        }
    }

    mStatus = Status.RUNNING;

    onPreExecute();

    mWorker.mParams = params;
    exec.execute(mFuture);

    return this;
}

幾個重點:

狀態檢查。 這也解釋了為什麼一個 AsyncTask 只能執行一次——執行完狀態變成 FINISHED,再呼叫就會拋出 IllegalStateException。

onPreExecute() 先跑。 這證明它確實早於 doInBackground,適合做一些前置準備工作。

參數被塞進 mWorker。 然後第 26 行呼叫 Executor 的 execute(),並把 mFuture 當作參數傳入。

那個 exec 是從哪來的?看 sDefaultExecutor 的定義:

public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

第三步:SerialExecutor 的串行機制

private static class SerialExecutor implements Executor {
    final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
    Runnable mActive;

    public synchronized void execute(final Runnable r) {
        mTasks.offer(new Runnable() {
            public void run() {
                try {
                    r.run();
                } finally {
                    scheduleNext();
                }
            }
        });
        if (mActive == null) {
            scheduleNext();
        }
    }

    protected synchronized void scheduleNext() {
        if ((mActive = mTasks.poll()) != null) {
            THREAD_POOL_EXECUTOR.execute(mActive);
        }
    }
}

傳入的 Runnable 其實就是我們的 mFuture(FutureTask 同時實作了 Future 與 Runnable)。execute() 會先把 mFuture 放進 mTasks,此時 mActive 還是 null,於是呼叫 scheduleNext(),從佇列取出第一個丟進線程池開始執行。

這裡有個關鍵設計:SerialExecutor 用一個 mActive 作為「 Currently 執行中」的標記,只有當前一任務跑完、在 finally 中呼叫 scheduleNext 時,才會取下一個。因此預設情況下多個 AsyncTask 是排隊串行執行的,而非並行。

第四步:mWorker 的 call 方法

public Result call() throws Exception {
    mTaskInvoked.set(true);
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    //noinspection unchecked
    Result result = doInBackground(mParams);
    Binder.flushPendingCommands();
    return postResult(result);
}

第 4 行把執行緒優先級調低為背景等級,第 6 行就是我們熟悉的 doInBackground()。重點來了:這段程式碼跑在另一條執行緒上,這正是為什麼在 doInBackground 裡不能操作 UI。最後把結果交給 postResult()。

第五步:用 Handler 切回主執行緒

private Result postResult(Result result) {
    @SuppressWarnings("unchecked")
    Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
            new AsyncTaskResult<Result>(this, result));
    message.sendToTarget();
    return result;
}

這裡就是我們熟悉的 Handler 了。它的實作如下:

private static class InternalHandler extends Handler {
    public InternalHandler() {
        super(Looper.getMainLooper());   // 綁定主執行緒的 Looper
    }

    @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
    @Override
    public void handleMessage(Message msg) {
        AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
        switch (msg.what) {
            case MESSAGE_POST_RESULT:
                // There is only one result
                result.mTask.finish(result.mData[0]);
                break;
            case MESSAGE_POST_PROGRESS:
                result.mTask.onProgressUpdate(result.mData);
                break;
        }
    }
}

Looper.getMainLooper() 就是答案所在——Handler 綁在主執行緒上,所以 handleMessage 自然在主執行緒執行。

由於我們發送的是 MESSAGE_POST_RESULT,會走到第 13 行的 finish():

private void finish(Result result) {
    if (isCancelled()) {
        onCancelled(result);
    } else {
        onPostExecute(result);
    }
    mStatus = Status.FINISHED;
}

一目了然:最後呼叫了我們的 onPostExecute(),並把結果傳過去,同時把狀態標記為 FINISHED。整個流程就是這樣。

那個沒被講到的 done() 方法

仔細看會發現,mFuture 實例化時覆寫的 done() 到目前都沒派上用場,它在整個流程中扮演什麼角色?

protected void done() {
    try {
        postResultIfNotInvoked(get());
    } catch (InterruptedException e) {
        android.util.Log.w(LOG_TAG, e);
    } catch (ExecutionException e) {
        throw new RuntimeException("An error occurred while executing doInBackground()",
                e.getCause());
    } catch (CancellationException e) {
        postResultIfNotInvoked(null);
    }
}

從命名應該能猜到,這個方法在整個非同步任務執行完之後被呼叫。在 Future 中,透過 get() 就能取得 mWorker 中 call 方法的回傳值。接著看 postResultIfNotInvoked:

private void postResultIfNotInvoked(Result result) {
    final boolean wasTaskInvoked = mTaskInvoked.get();
    if (!wasTaskInvoked) {
        postResult(result);
    }
}

你可能會問:postResult() 怎麼被呼叫了兩次?看方法名就明白了——「post result if not invoked」,這次的呼叫是保險機制,防止 call() 因故沒執行到 postResult 時結果遺失。

開關就是 mTaskInvoked,它是個 AtomicBoolean。在 call 方法開頭我們看過:

mTaskInvoked.set(true);

所以正常流程下,執行過 call 之後這裡會讀到 true,後續就不會重複執行,從而保證 postResult 只被呼叫一次。

總結

整條鏈路串起來是:execute → SerialExecutor 排隊 → 線程池執行 mFuture → mWorker.call → doInBackground(背景執行緒)→ postResult → InternalHandler(主執行緒)→ onPostExecute。

理解這條鏈路有幾個實用價值:知道預設是串行的,就明白為什麼多個下載任務會互相等待,此時應改用 executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ...);知道 Handler 綁在主 Looper,就明白為什麼 onProgressUpdate 能安全更新 UI;也知道它為何只能執行一次。

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