Asynctask解析以及注意事項

/*
    說到AsyncTask這個類,好多人其實不太瞭解。最近看了下代碼,把心得分享給大家。
    AsyncTask的execute的執行流程爲
    先調用ThreadPoolExecutor.execute(mFuture);
    然後ThreadPoolExecutor.execute(mFuture) 會調用ThreadPoolExecutor.addWorker(mFuture);
    最後ThreadPoolExecutor.addWorker(mFuture)會調用mFuture的run()方法,run方法中就是該線程要執行操作的地方
    到此我們來關注一下mFuture,AsyncTask中的mFuture是一個FutureTask,FutureTask實現了Future<V>, Runnable兩個接口,
    Future 表示異步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,並獲取計算的結果,計算完成後只能使用 get 方法來獲取結果。
    mFuture以mWorker作爲參數
    現看mFuture的構造方法:
public void run() {
    sync.innerRun();
}

    sync是什麼呢?Sync類是一個內部類,我們看看它的初始化
public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    sync = new Sync(callable);
}
    在看看sync.innerRun()方法:
void innerRun() {
    if (!compareAndSetState(READY, RUNNING))
        return;

    runner = Thread.currentThread();
    if (getState() == RUNNING) { // recheck after setting thread
        V result;
        try {
            result = callable.call();
        } catch (Throwable ex) {
            setException(ex);
            return;
        }
        set(result);
    } else {
        releaseShared(0); // cancel
    }
}
    從代碼可以看到,其實最終是調用了callable.call()這個方法。
    從AsyncTask中我們可以知道,我們傳入的Callable是我們的WorkerRunnable
    所以,我們會調用WorkerRunnable的call()方法,在call方法裏面
    返回postResult(doInBackground(mParams));
    通知UI線程更新,這就是調用過程
Notes:
1:
    因爲AsyncTask裏面的內部handler和Executor都是靜態變量,所以,他們控制着所有的子類。
2:
    我們可以通過AsyncTask.execute()方法來調用系統默認的線程池來處理當前的任務,
    系統默認的線程池用的是SerialExecutor.這個線程池控制所有任務按順序執行。也就是一次只執行一條.
    當前執行完了,才執行下一條.2.3平臺以前是所有的任務併發執行,這會導致一種情況,就是其中一條任務執行出問題了,會引起其他任務
    出現錯誤.
3:
    AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)你也可以採用這個系統提供的線程池來處理你的任務
    默認這個線程池是併發處理任務的,也就是不按順序來.核心爲5條,最大128條
4:
    你也可以使用自定義的線程池,這樣就可以即使的執行你的任務需求,而不是用系統的。因爲用系統默認的線程池可以需要等待,它默認
    是按順序執行(THREAD_POOL_EXECUTOR)或者最多執行5個(SerialExecutor).
    自己使用自定義線程池方式如下:
    new AsyncTask.executeOnExecutor((ExecutorService)Executors.newCachedThreadPool()).
5:  不要隨意使用AsyncTask,除非你必須要與UI線程交互.默認情況下使用Thread即可,要注意需要將線程優先級調低.
    從google官方文檔你也可以看到,AsyncTasks should ideally be used for short operations (a few seconds at the most.)
    AsyncTask適合處理短時間的操作,長時間的操作,比如下載一個很大的視頻,這就需要你使用自己的線程來下載,不管是斷點下載還是其它的.
    當然,如果你需要開啓自定義的很多線程來處理你的任務,切記你此時可以考慮自定義線程池
 */
public abstract class AsyncTask<Params, Progress, Result> {
    private static final String LOG_TAG = "AsyncTask";
    // 核心線程數是要
    private static final int CORE_POOL_SIZE = 5;
    // 最大線程數支持128
    private static final int MAXIMUM_POOL_SIZE = 128;
    // 這個參數的的意思是當前線程池裏面的thread如果超過了規定的核心線程5,如果有線程的空閒時間超過了這個數值,
    // 數值的單位自己指定,就回收該線程的資源,達到動態調整線程池資源的目的.
    private static final int KEEP_ALIVE = 1;
    // ThreadFactory是用來在線程池中構建新線程的方法.可以看到每次構建一個方法,名字都不同.爲"AsyncTask # 1++".
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        }
    };
    // 線程池所使用的緩衝隊列.FIFO,它用於存放如果當前線程池中核心線程已滿,此時來的任務都被放到緩衝隊列中等待被處理.
    // 初始化容量爲10
    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(10);

    /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    // 線程池的初始化,指定了核心線程5,最大線程128,超時1s,緩衝隊列等, 你在使用asyncTask的時候,可以傳入這個參數,
    // 就可以讓多條線程併發的執行了.比如:executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
    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 final int MESSAGE_POST_RESULT = 0x1;
    private static final int MESSAGE_POST_PROGRESS = 0x2;
    // 這個InternalHandler就是用來是UI線程打交道的。可以看到它是個靜態的變量。也就是說誰第一次調用它,下一次另一個
    // 線程來調用,也不會實例話這個常量.關於這個handler,默認asynctask都是從主線程中調用的,所以,這個Handler默認
    // 獲得了主線程的Looper,所以就能和主線程來交互. Notes:假如你在一個子線程中構建了自己的Looper並使用Asynctask,
    // 應該會出問題,因爲此時這個Handler就屬於子線程了,就不能去操控UI的操作.這應該算是AsyncTask的Bug.網上有人說
    // 在4.0上運行沒問題,2.3會有問題,原因是因爲4.0中的ActivityThread.main方法裏面最先用主線程的Looper來初始化了這個
    // AsyncTask。理論上Asynctask應該判斷當前的Looper如果不是MainThread的Looper的話,拋出異常,遺憾的是,
    // google沒有考慮到這裏,只是在文檔中要求必須在主線程中調用,其實,很不好!
    private static final InternalHandler sHandler = new InternalHandler();

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    // 自定義的靜態內部類
    private final WorkerRunnable<Params, Result> mWorker;
    // 其實就是也一個Runnable,實現了這個接口
    private final FutureTask<Result> mFuture;

    // 默認爲pending狀態。
    private volatile Status mStatus = Status.PENDING;
    // 原子操作,專門用來處理併發訪問,就可以不用synchronized
    private final AtomicBoolean mCancelled = new AtomicBoolean();
    private final AtomicBoolean mTaskInvoked = new AtomicBoolean();

    private static class SerialExecutor implements Executor {
        // ArrayDeque是一個雙向隊列,我們來理解下這個線程池是如何做到一次只
        // 執行一條任務的.比如此時有多處先後都調用了AsyncTask.execute()方法,
        // 對第一條最先到的任務來說,首先自己被假如到了隊列中,因爲第一次mActive == null成立,
        // 所以執行THREAD_POOL_EXECUTOR.execute(mActive).且mActive 此時不等於Null.
        // 所以第二條任務來的時候,只是被加入到了隊列中,並不會執行.除非第一條任務執行完了,在它的finnally方法中
        // 調用scheduleNext()去再次從對列中取出下一條任務來執行.這樣就實現了所有任務按順序執行的功能.
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
            // 把線程offer到隊列中
            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);
            }
        }
    }

    /**
     * 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,
    }

    /** @hide Used to force static handler to be created. */
    public static void init() {
        sHandler.getLooper();
    }

    /** @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並複寫call方法,後面會介紹什麼時候調用
        mWorker = new WorkerRunnable<Params, Result>() {
            // 這個方法就是當你嗲用excutor.excute()方法後執行的方法。至於是如何執行的,我們後面會分析
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                // 將線程優先級設置爲後臺線程,默認和主線程優先級一樣,如果不這樣做,也會降低程序性能.因爲會優先
                // 搶佔cpu資源.所以,如果你在程序中不使用asyncTask而是自己new 一條線程出來,記得把線程的優先級設置爲
                // 後臺線程
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //這個地方調用了我們自己實現的doInBackground
                return postResult(doInBackground(mParams));
            }
        };
       // 用mWorker創建一個可取消的異步計算任務
        mFuture = new FutureTask<Result>(mWorker) {
            @Override
            // 當任務不管是正常終止、異常或取消而完成的,都回調此方法, 即isDone()爲true時,isDone不管成功還是失敗都
            // 返回true
            protected void done() {
                try {
                    // 如果當前的task沒有被invoke,就被finish掉
                    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);
                }
            }
        };
    }

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

    // 當doInBackground結束了,調用PostResult發佈結果
    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = sHandler.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
     */
    // 用戶自己實現
    protected abstract Result doInBackground(Params... params);

    /**
     * Runs on the UI thread before {@link #doInBackground}.
     *
     * @see #onPostExecute
     * @see #doInBackground
     */
    // 用戶自己實現
    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"})
    // 用戶自己實現
    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"})
    // 用戶自己實現
    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"})
    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()
     */
    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)
     */
    // 這個方法就是用戶調用的excute方法,默認採用asynctask自帶的線程池串行執行任務
    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[])
     */
    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;
        // 調用用戶--UI線程---自己實現的方法
        onPreExecute();

        mWorker.mParams = params;
        // 這個方法就會調用前面的mWorker的call方法
        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[])
     */
    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 note be called if the task has been
     * canceled.
     *
     * @param values The progress values to update the UI with.
     *
     * @see #onProgressUpdate
     * @see #doInBackground
     */
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            sHandler.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;
    }

    //  與UI交互
    private static class InternalHandler extends Handler {
        @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 static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }

    @SuppressWarnings({"RawUseOfParameterizedType"})
    // 存儲異步執行結果的類
    private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章