從原始碼解析-掌握AsyncTask工作原理 為什麼序列執行和記憶體洩漏

硬剛平底鍋發表於2018-06-21

什麼是AsyncTask

它本質上是一個封裝了執行緒池和Handler的非同步框架;它內部使用一個執行緒池,序列執行每一個執行緒,執行緒生命週期不用開發者管理,用來執行非同步任務,通過Handler來進行回撥更新UI

這一套業務也可以使用Thread來做,但是使用Thread有些麻煩,每次使用都要自己new一個執行緒,要自己管理其生命週期,而且android還不允許在非主執行緒的執行緒更新UI,這樣的話thread執行得到的結果如果需要更新UI可能還需要發一個handler通知主執行緒更新介面,程式碼寫起來比較凌亂不如asynctask一目瞭然好維護。

AsyncTask的原始碼

public abstract class AsyncTask<Params, Progress, Result> {
    private static final String LOG_TAG = "AsyncTask";

    //獲取CPU數量
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    //確定執行緒池核心執行緒數量
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    //確定執行緒池執行緒最大數量
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 1;

    //執行緒工廠,下面例項化執行緒池要使用
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        //提供原子操作的Integer類,確保getAndIncrement()執行緒安全
        private final AtomicInteger mCount = new AtomicInteger(1);
        //重寫該方法,確定新增加的執行緒的執行緒名,就是增加一個標識,表明這個執行緒是AsyncTask的
        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        }
    };

    /**
     * BlockingQueue 是Concurrent包中的一種阻塞佇列
     * 當BlockingQueue為空, 從佇列取資料時會讓執行緒等待狀態,直到能取出非空的資料,執行緒會被喚醒。
     * 當BlockingQueue是滿的,存資料到佇列時執行緒也會進入等待狀態,直到有空間,執行緒才會被喚醒。
     * 在這裡是存放待執行的Runnable,容量為128
     */
    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);

    /**
     * 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.
     * AsyncTask內部實現的執行緒池,序列執行執行緒
     */
    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

    /**
     * Handler訊息的what
     */
    private static final int MESSAGE_POST_RESULT = 0x1;
    private static final int MESSAGE_POST_PROGRESS = 0x2;

    //用原子符修飾sDefaultExecutor,並且將SERIAL_EXECUTOR賦值給sDefaultExecutor
    //AsyncTask內部使用它進行執行任務
    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    //主執行緒的Handler
    private static InternalHandler sHandler;

    /**
     * AstncTask內部類,實現了Callable介面
     * 內部例項了一個儲存引數的mParams陣列
     * Callable介面內部有一個call方法,方法裡是開發者具體邏輯實現,與Runnable介面類似,
     * 只不過Runnable裡的run方法沒有返回值,而call方法有返回值
     */
    private final WorkerRunnable<Params, Result> mWorker;
    /**
     * FutureTask類實現了Runnable介面和Future介面,且內部維護了一個Callable物件,
     * FutureTask的建構函式中需要傳入一個Callable物件以對其進行例項化
     * Executor的execute方法接收一個Runnable物件,由於FutureTask實現了Runnable介面,
     * 所以可以把一個FutureTask物件傳遞給Executor的execute方法去執行。
     * 當任務執行完畢的時候會執行FutureTask的done方法,我們可以在這個方法中寫一些邏輯處理。
     * 在任務執行的過程中,我們也可以隨時呼叫FutureTask的cancel方法取消執行任務,任務取消後也會執行FutureTask的done方法。
     * 我們也可以通過FutureTask的get方法阻塞式地等待任務的返回值(即Callable的call方法的返回值),
     * 如果任務執行完了就立即返回執行的結果,否則就阻塞式等待call方法的完成。
     */
    private final FutureTask<Result> mFuture;

    //標識當前正在執行的執行緒的狀態
    private volatile Status mStatus = Status.PENDING;
    /**
     * 提供原子操作的Boolean型別,保證執行緒安全
     * mCancelled表示任務是否被取消
     * mTaskInvoked是否開始執行了
     */
    private final AtomicBoolean mCancelled = new AtomicBoolean();
    private final AtomicBoolean mTaskInvoked = new AtomicBoolean();

    /**
     * 自定義一個執行緒池,序列執行任務
     * 序列執行邏輯就是:
     * 首先通過execute(Params... params)方法執行到這個類的execute;
     * 然後將mFuture封裝成一個Runnable(裡面的run方法的邏輯就是先執行mFuture的run方法,
     * 執行結束後就通過scheduleNext()方法取出下一個任務執行,迴圈往復)新增到佇列裡;
     * 但是一開始mActive肯定為null,所以就通過scheduleNext()方法取出上一步新增的任務去執行;
     * 以後就迴圈執行run方法裡的邏輯
     */
    private static class SerialExecutor implements Executor {
        /**
         * ArrayDeque是一個雙向佇列,能夠同時在兩端進行插入刪除操作,
         * 不過它的內部沒有做同步操作,雖然效率上要高於linkedList, vector等,但是存在併發問題
         * 需要開發者自己做維護,這裡SerialExecutor就是序列執行,所以沒有併發問題
         * 在這裡存放Runnable,佇列容量沒有限制
         */
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        //當前正在執行的任務
        Runnable mActive;

        //實現Executor的execute方法,用於序列執行任務
        public synchronized void execute(final Runnable r) {
            //通過佇列的offer方法將封裝後的r新增到佇列的最後
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
                        r.run();
                    } finally {
                        //r執行結束後執行下一個任務
                        scheduleNext();
                    }
                }
            });
            //當前沒有執行任務,就執行這個方法去取任務執行
            if (mActive == null) {
                scheduleNext();
            }
        }
        //返回並刪除佇列的頭部第一個元素,然後把執行緒交給執行緒池執行
        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }

    /**
     * Indicates the current status of the task. Each status will be set only once
     * during the lifetime of a task.
     */
    public enum Status {
        /**
         * Indicates that the task has not been executed yet.
         * 表示任務還沒有開始執行
         */
        PENDING,
        /**
         * Indicates that the task is running.
         * 表示任務正在執行
         */
        RUNNING,
        /**
         * Indicates that {@link AsyncTask#onPostExecute} has finished.
         * 表示任務執行結束
         */
        FINISHED,
    }

    //獲取Handler
    private static Handler getHandler() {
        synchronized (AsyncTask.class) {
            if (sHandler == null) {
                sHandler = new InternalHandler();
            }
            return sHandler;
        }
    }

    /** @hide */
    public static void setDefaultExecutor(Executor exec) {
        sDefaultExecutor = exec;
    }

    /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        //例項化mWorker物件,
        mWorker = new WorkerRunnable<Params, Result>() {
            //實現call方法,執行任務
            public Result call() throws Exception {
                //將mTaskInvoked設定為true,表明任務開始執行
                mTaskInvoked.set(true);
                //將該執行緒設定為後臺執行緒
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //這個方法就是我們具體邏輯的實現,然後獲取返回結果
                Result result = doInBackground(mParams);
                Binder.flushPendingCommands();
                //將返回結果傳遞給postResult
                return postResult(result);
            }
        };

        //當mFuture被sDefaultExecutor執行的時候,FutureTask內部run方法中的callable物件會呼叫call方法,
        // 就會走到上面的mWorker物件的call方法,方法走完,FutureTask內部run方法中會呼叫set(result)方法或者setException(ex)方法
        // 這兩個方法裡都會回撥done()方法。
        mFuture = new FutureTask<Result>(mWorker) {
            //任務執行結束或者被取消都會呼叫done方法
            @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);
                }
            }
        };
    }

    private void postResultIfNotInvoked(Result result) {
        final boolean wasTaskInvoked = mTaskInvoked.get();
        if (!wasTaskInvoked) {
            //call方法沒有被呼叫執行這個
            postResult(result);
        }
    }

    /**
     * AsyncTaskResult是一個內部類,裡面包含執行任務的AsyncTask物件和返回的資料
     * 將結果封裝到AsyncTaskResultHandler中傳送出去
     * @param result
     * @return
     */
    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

    /**
     * Returns the current status of this task.
     *
     * @return The current status.
     */
    public final Status getStatus() {
        return mStatus;
    }

    /**
     * Override this method to perform a computation on a background thread. The
     * specified parameters are the parameters passed to {@link #execute}
     * by the caller of this task.
     *
     * This method can call {@link #publishProgress} to publish updates
     * on the UI thread.
     *
     * @param params The parameters of the task.
     *
     * @return A result, defined by the subclass of this task.
     *
     * @see #onPreExecute()
     * @see #onPostExecute
     * @see #publishProgress
     */
    @WorkerThread
    protected abstract Result doInBackground(Params... params);

    /**
     * Runs on the UI thread before {@link #doInBackground}.
     *
     * @see #onPostExecute
     * @see #doInBackground
     */
    @MainThread
    protected void onPreExecute() {
    }

    /**
     * <p>Runs on the UI thread after {@link #doInBackground}. The
     * specified result is the value returned by {@link #doInBackground}.</p>
     * 
     * <p>This method won't be invoked if the task was cancelled.</p>
     *
     * @param result The result of the operation computed by {@link #doInBackground}.
     *
     * @see #onPreExecute
     * @see #doInBackground
     * @see #onCancelled(Object) 
     */
    @SuppressWarnings({"UnusedDeclaration"})
    @MainThread
    protected void onPostExecute(Result result) {
    }

    /**
     * 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"})
    @MainThread
    protected void onProgressUpdate(Progress... values) {
    }

    /**
     * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
     * {@link #doInBackground(Object[])} has finished.</p>
     * 
     * <p>The default implementation simply invokes {@link #onCancelled()} and
     * ignores the result. If you write your own implementation, do not call
     * <code>super.onCancelled(result)</code>.</p>
     *
     * @param result The result, if any, computed in
     *               {@link #doInBackground(Object[])}, can be null
     * 
     * @see #cancel(boolean)
     * @see #isCancelled()
     */
    @SuppressWarnings({"UnusedParameters"})
    @MainThread
    protected void onCancelled(Result result) {
        onCancelled();
    }    
    
    /**
     * <p>Applications should preferably override {@link #onCancelled(Object)}.
     * This method is invoked by the default implementation of
     * {@link #onCancelled(Object)}.</p>
     * 
     * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
     * {@link #doInBackground(Object[])} has finished.</p>
     *
     * @see #onCancelled(Object) 
     * @see #cancel(boolean)
     * @see #isCancelled()
     */
    @MainThread
    protected void onCancelled() {
    }

    /**
     * Returns <tt>true</tt> if this task was cancelled before it completed
     * normally. If you are calling {@link #cancel(boolean)} on the task,
     * the value returned by this method should be checked periodically from
     * {@link #doInBackground(Object[])} to end the task as soon as possible.
     *
     * @return <tt>true</tt> if task was cancelled before it completed
     *
     * @see #cancel(boolean)
     */
    public final boolean isCancelled() {
        return mCancelled.get();
    }

    /**
     * <p>Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when <tt>cancel</tt> is called,
     * this task should never run. If the task has already started,
     * then the <tt>mayInterruptIfRunning</tt> parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.</p>
     * 
     * <p>Calling this method will result in {@link #onCancelled(Object)} being
     * invoked on the UI thread after {@link #doInBackground(Object[])}
     * returns. Calling this method guarantees that {@link #onPostExecute(Object)}
     * is never invoked. After invoking this method, you should check the
     * value returned by {@link #isCancelled()} periodically from
     * {@link #doInBackground(Object[])} to finish the task as early as
     * possible.</p>
     *
     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
     *        task should be interrupted; otherwise, in-progress tasks are allowed
     *        to complete.
     *
     * @return <tt>false</tt> if the task could not be cancelled,
     *         typically because it has already completed normally;
     *         <tt>true</tt> otherwise
     *
     * @see #isCancelled()
     * @see #onCancelled(Object)
     */
    public final boolean cancel(boolean mayInterruptIfRunning) {
        mCancelled.set(true);
        return mFuture.cancel(mayInterruptIfRunning);
    }

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @return The computed result.
     *
     * @throws CancellationException If the computation was cancelled.
     * @throws ExecutionException If the computation threw an exception.
     * @throws InterruptedException If the current thread was interrupted
     *         while waiting.
     */
    public final Result get() throws InterruptedException, ExecutionException {
        return mFuture.get();
    }

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result.
     *
     * @param timeout Time to wait before cancelling the operation.
     * @param unit The time unit for the timeout.
     *
     * @return The computed result.
     *
     * @throws CancellationException If the computation was cancelled.
     * @throws ExecutionException If the computation threw an exception.
     * @throws InterruptedException If the current thread was interrupted
     *         while waiting.
     * @throws TimeoutException If the wait timed out.
     */
    public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
            ExecutionException, TimeoutException {
        return mFuture.get(timeout, unit);
    }

    /**
     * Executes the task with the specified parameters. The task returns
     * itself (this) so that the caller can keep a reference to it.
     * 
     * <p>Note: this function schedules the task on a queue for a single background
     * thread or pool of threads depending on the platform version.  When first
     * introduced, AsyncTasks were executed serially on a single background thread.
     * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
     * to a pool of threads allowing multiple tasks to operate in parallel. Starting
     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
     * executed on a single thread to avoid common application errors caused
     * by parallel execution.  If you truly want parallel execution, you can use
     * the {@link #executeOnExecutor} version of this method
     * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
     * on its use.
     *
     * <p>This method must be invoked on the UI thread.
     *
     * @param params The parameters of the task.
     *
     * @return This instance of AsyncTask.
     *
     * @throws IllegalStateException If {@link #getStatus()} returns either
     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
     *
     * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
     * @see #execute(Runnable)
     */
    @MainThread
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

    /**
     * Executes the task with the specified parameters. The task returns
     * itself (this) so that the caller can keep a reference to it.
     * 
     * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
     * allow multiple tasks to run in parallel on a pool of threads managed by
     * AsyncTask, however you can also use your own {@link Executor} for custom
     * behavior.
     * 
     * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
     * a thread pool is generally <em>not</em> what one wants, because the order
     * of their operation is not defined.  For example, if these tasks are used
     * to modify any state in common (such as writing a file due to a button click),
     * there are no guarantees on the order of the modifications.
     * Without careful work it is possible in rare cases for the newer version
     * of the data to be over-written by an older one, leading to obscure data
     * loss and stability issues.  Such changes are best
     * executed in serial; to guarantee such work is serialized regardless of
     * platform version you can use this function with {@link #SERIAL_EXECUTOR}.
     *
     * <p>This method must be invoked on the UI thread.
     *
     * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as a
     *              convenient process-wide thread pool for tasks that are loosely coupled.
     * @param params The parameters of the task.
     *
     * @return This instance of AsyncTask.
     *
     * @throws IllegalStateException If {@link #getStatus()} returns either
     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
     *
     * @see #execute(Object[])
     */
    @MainThread
    public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
            Params... params) {
        if (mStatus != Status.PENDING) {
            switch (mStatus) {
                case RUNNING:
                    //如果這個AsyncTask已經執行了還執行這個方法就丟擲異常
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task is already running.");
                case FINISHED:
                    //如果這個AsyncTask已經執行結束了還執行這個方法就丟擲異常
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task has already been executed "
                            + "(a task can be executed only once)");
            }
        }

        //將該任務標識為正在執行
        mStatus = Status.RUNNING;
        //回撥該方法,開發者可在這個方法裡做一些準備工作
        onPreExecute();
        //將開發者傳入的引數賦值給mWorker物件的內部變數
        mWorker.mParams = params;
        //讓sDefaultExecutor執行mFuture,其實就是SerialExecutor這個類去執行execute(final Runnable r)方法,
        //因為mFuture實現了Runnable介面,所以執行緒池可以執行這個物件
        exec.execute(mFuture);

        return this;
    }

    /**
     * Convenience version of {@link #execute(Object...)} for use with
     * a simple Runnable object. See {@link #execute(Object[])} for more
     * information on the order of execution.
     *
     * @see #execute(Object[])
     * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
     */
    @MainThread
    public static void execute(Runnable runnable) {
        sDefaultExecutor.execute(runnable);
    }

    /**
     * This method can be invoked from {@link #doInBackground} to
     * publish updates on the UI thread while the background computation is
     * still running. Each call to this method will trigger the execution of
     * {@link #onProgressUpdate} on the UI thread.
     *
     * {@link #onProgressUpdate} will not be called if the task has been
     * canceled.
     *
     * @param values The progress values to update the UI with.
     *
     * @see #onProgressUpdate
     * @see #doInBackground
     */
    @WorkerThread
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

    private void finish(Result result) {
        if (isCancelled()) {
            //如果任務被取消了,回撥該方法
            onCancelled(result);
        } else {
            //如果任務正常走完,就回撥該方法
            onPostExecute(result);
        }
        //將該任務狀態設定為結束
        mStatus = Status.FINISHED;
    }

    private static class InternalHandler extends Handler {
        public InternalHandler() {
            //獲取主執行緒的Looper,將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:
                    //開發者通過呼叫publishProgress,會轉到這裡將過程回撥給開發者
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }

    private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }

    /**
     * 將AsyncTask和返回資料封裝成一個物件,用於Handler通訊時使用
     * @param <Data>
     */
    @SuppressWarnings({"RawUseOfParameterizedType"})
    private static class AsyncTaskResult<Data> {
        //具體執行任務的AsyncTask
        final AsyncTask mTask;
        //儲存資料,一個可變長度的陣列
        final Data[] mData;

        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }
}

AsyncTask為什麼是序列執行任務,其中的原理在上面的註釋中已經解釋了

而有的文章說它是並行執行任務是為什麼呢?你們可以看到上面有一個方法

 	/** @hide */
    public static void setDefaultExecutor(Executor exec) {
        sDefaultExecutor = exec;
    }

這個方法我們肯定是沒有呼叫過的,那是誰呼叫的呢?其實是應用剛啟動的時候在ActivityThread的handleBindApplication方法呼叫的(原文出處),裡面有這樣一句

// 如果sdk版本在Android3.1.x(API12)或更早版本,需要設定Asynctask中使用的執行緒池,這樣任務是並行執行,在高版本是序列執行
if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
  AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

顯然這個THREAD_POOL_EXECUTOR是這樣的

/**
     * 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);

所以AsyncTask在API12及以前是序列執行任務的


總結機制原理

  • 獲取cpu數量,核心執行緒數量,執行緒池最大執行緒數量,例項化了一個執行緒工廠(標識新執行緒的名稱),一個存放執行緒池的阻塞佇列,最後構建一個執行緒池,這些東西都是靜態的,不會每次new Asynctask都會例項化
  • AsyncTask內部自己實現了一個執行緒池SerialExecutor類,從這個名字也可以看出來,這是一個序列執行器,平時看到很多分析部落格還在說AsyncTask可以同時執行多個執行緒,其實這是不對的,只有老早的版本才會這樣。至於序列的實現原理,上面註釋已經很清楚了。之後把這個類的引用賦值給sDefaultExecutor
  • 接下來就是AsyncTask構造方法了,做了兩件事,第一件就是例項化了一個WorkerRunnable物件,它是內部類,實現了Callable介面,並且定義了一個存放開發者傳入的引數的陣列,重寫了call方法,這裡就是耗時操作的執行地,並且將執行結果返回,最終會回撥到onPostExecute(Result result);第二件事就是例項化一個FutureTask物件,重寫done方法,當任務執行結束或者出現異常會回撥這個方法。
  • 最後就是兩個最重要的方法了,開發者new了一個AsyncTask物件後呼叫它的execute(Params… params)方法,這裡走到了executeOnExecutor(Executor exec,Params… params)方法,第一個引數是sDefaultExecutor,也就是SerialExecutor物件,第二個引數是開發者傳入的引數。非同步任務執行邏輯將FutureTask丟到SerialExecutor的類的execute方法中,這個方法將FutureTask又封裝成了一個Runnable,這個Runnable的run方法邏輯就是執行FutureTask的run方法(這裡面會回撥WorkerRunnable的call方法,這裡面會回撥doInBackground;執行完畢後呼叫FutureTask的done方法),執行結束後呼叫scheduleNext()方法迴圈往復。

AsyncTask注意事項

  • 記憶體洩漏
    其實這個問題跟Handler記憶體洩漏原因是一樣的,都是非靜態內部類持有外部類activity的引用
    具體原因和解決辦法可以去這篇部落格檢視
    Android之Handler原始碼分析/Looper,Message,Messagequeue三者關係/Handler引起的記憶體洩漏
  • 生命週期
    AsyncTask的生命週期並不是跟隨Activity的生命週期,當Activity銷燬的時候,需要處理AsyncTask,以防內部的子執行緒造成記憶體洩漏,所以需要及時呼叫AsyncTask.cancel(boolean mayInterruptIfRunning)取消非同步任務
  • 結果丟失
    當應用發生記憶體重啟的時候,之前的AsyncTask會持有之前的activity的引用,這時候再呼叫Activity就會異常,這時候需要進行判斷Activity是否位null
  • 序列 並行
    在Android1.6之前的版本是序列的,在1.6-2.3改成了並行,在2.3以後為了系統穩定又改成了序列,但是也提供了一個方法execute(Runnable runnable)達到並行的需求

相關文章