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

Android AsyncTask 執行機制源碼剖析與完整流程示例

編輯:關於 Android 程式設計

AsyncTask 幾乎是每個 Android 開發者最早接觸的執行緒工具,但多數人只會照著範式呼叫 execute(),對它背後如何切換執行緒、如何把結果送回主執行緒並不清楚。本文直接從原始碼切入,把這條呼叫鏈路攤開來看。

進入點:execute 與 executeOnExecutor

對外暴露的 execute 只是個薄殼,真正的邏輯都在 executeOnExecutor 裡:

 public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); } 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; } 

這段程式碼說明了兩件事:一是 onPreExecute() 由框架自動呼叫,不需要你手動觸發;二是同一個 AsyncTask 實例只能執行一次,重複呼叫會直接拋出 IllegalStateException。

SerialExecutor:任務排隊的守門人

Executor 本身是個再簡單不過的介面:

 public interface Executor { void execute(Runnable command); } 

預設實作是 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); } } } 

流程就清楚了:任務先被包一層放進 mTasks 佇列,若目前沒有任務在跑就立刻呼叫 scheduleNext() 取出頭部交給真正的執行緒池;每個任務的 finally 區塊都會再呼叫一次 scheduleNext(),形成環環相扣的序列執行。這也是為什麼預設情況下多個 AsyncTask 不會真正並行。

兩個執行緒池與一個 Handler

 /** * An {@link Executor} that can be used to execute tasks in parallel. */ public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); /** * An {@link Executor} that executes tasks one at a time in serial * order. This serialization is global to a particular process. */ public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static InternalHandler sHandler; 

三者分工明確:SERIAL_EXECUTOR 負責排隊,THREAD_POOL_EXECUTOR 負責真正跑工作,InternalHandler 負責把結果送回主執行緒。

建構子:mWorker 與 mFuture

 public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked return postResult(doInBackground(mParams)); } }; 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 occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; } 

熟悉的 doInBackground 就在 call() 裡被呼叫,算完之後交給 postResult。

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

InternalHandler 綁在主執行緒的 Looper 上,收到 MESSAGE_POST_RESULT 後呼叫 finish():

 private static class InternalHandler extends Handler { public InternalHandler() { super(Looper.getMainLooper()); } @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; } } } private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } 

串起來看完整流程

寫法上就是 new 一個子類別再 execute(params)。建構階段只準備了 mWorker 與 mFuture 兩個變數;execute 先跑 onPreExecute,接著交給 SerialExecutor 排隊;SerialExecutor 把任務丟進 mTasks 並轉交 THREAD_POOL_EXECUTOR;背景執行緒觸發 call(),在其中呼叫 doInBackground;結果經 postResult 丟給主執行緒的 Handler,最後由 finish() 決定呼叫 onPostExecute 還是 onCancelled。

那 onProgressUpdate 呢?

通篇看下來似乎沒看到 onProgressUpdate 被觸發,原因藏在它的宣告上:

 /** * Runs on the UI thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values The values indicating progress. * * @see #publishProgress * @see #doInBackground */ @SuppressWarnings({"UnusedDeclaration"}) protected void onProgressUpdate(Progress... values) { } 

也就是說,它必須由 publishProgress 主動觸發才會被呼叫。而 publishProgress 的呼叫時機,doInBackground 的註解寫得很明白——就在這個方法裡自行呼叫即可:

 protected final void publishProgress(Progress... values) { if (!isCancelled()) { getHandler().obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget(); } } 

它同樣是發訊息給 InternalHandler,只是 what 換成 MESSAGE_POST_PROGRESS,於是走到 onProgressUpdate 這一分支。整個機制就是這樣,理解了這條鏈路,自訂執行緒池或改用其他非同步方案時心裡都會有底。

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

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