AsyncTask使用及內部實現分析

一、使用方法

AsyncTask通常用于實現在后臺線程中完成耗時操作,然后在主線程中更新UI。

繼承AsyncTask需要指定3個泛型參數:
AsyncTask<Params, Progress, Result>

  • Params: 啟動任務執行的輸入參數的類型
  • Progress: 后臺任務完成的進度值得類型
  • Result: 后臺執行任務完成后返回結果的類型

使用AsyncTask的主要方法:

  • protected String doInBackground(Params... params)
    在后臺線程池中執行,可以調用publishProgress(Progress... values)方法觸發onProgressUpdate方法,從而更新任務任務進度
  • protected void onProgressUpdate(Progress... values)
    在UI線程執行,更新進度條等UI
  • protected void onPreExecute()
    在doInBackground方法之前UI線程執行,通常用于完成初始化工作。
  • protected void onPostExecute(Result result)
    在UI線程執行,在doInBackground方法之后會自動調用,并將doInBackground的返回值傳給該方法。

使用AsyncTask必須遵守以下原則:

  • 必須在UI線程創建AsyncTask實例,API26之后不需要
  • 必須在UI線程中調用AsyncTask的execute()方法,因為onPreExecute需要在主線程回調
  • 每個AsyncTask在后臺任務執行完成前只能被執行一次,多次調用會引發異常

demo

public class MainActivity extends AppCompatActivity {
    private TextView show = null;
    private Button button = null;
    private final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show = (TextView)findViewById(R.id.show);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    download();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void download() throws MalformedURLException {
        MyAsyncTask task = new MyAsyncTask(this);
        //AsyncTask第一個參數為Void,如果不是Void,execute方法需要傳入參數。
        task.execute();
    }




    class MyAsyncTask extends AsyncTask<Void, Integer, String> {

        ProgressDialog pDialog;
        int hasRead = 0;
        Context mContext;
        public MyAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected String doInBackground(Void... params) {
            StringBuilder sb = new StringBuilder();
            try{
                while (hasRead < 100) {
                    hasRead++;
                    sb.append(hasRead + " ");
                    publishProgress(hasRead);
                    Thread.sleep(200);
                }
                return sb.toString();
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }



        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(mContext);
            pDialog.setTitle("任務正在執行中");
            pDialog.setMessage("任務正在執行中, 敬請等待...");
            pDialog.setCancelable(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setIndeterminate(false);
            pDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            show.setText("已經讀取了【" + values[0] + "】行!");
            pDialog.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            show.setText(s);
            if (hasRead == 100) {
                pDialog.dismiss();
            }

        }
    }
}

[圖片上傳失敗...(image-c5125d-1551414183649)]
AsyncTaskTest.jpg

二、AsyncTask源碼分析

首先來看下構造函數

/frameworks/base/core/java/android/os/AsyncTask.java

     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        this((Looper) null);
    }

    /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     *
     * @hide
     */
    public AsyncTask(@Nullable Handler handler) {
        this(handler != null ? handler.getLooper() : null);
    }

    /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     *
     * @hide
     */
    public AsyncTask(@Nullable Looper callbackLooper) {
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    postResult(result);
                }
                return 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);
                }
            }
        };
    }

構造函數中首先創建了一個WorkerRunnable對象,我們看下WorkerRunnable定義:

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

WorkerRunnable繼承自Callable接口,Callable接口跟Runnable接口類似,只是其中的call方法帶返回值

public interface Runnable {
    public abstract void run();
}

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

回到AsyncTask構造函數中,在WorkerRunnable的call方法中調用了doInBackground,doInBackground執行完后把結果傳給postResult方法。繼續往下看創建了FutureTask對象,FutureTask可以通過調用ExecutorService.submit執行參數Callable中的任務,也可以用于獲得Callable任務的執行結果、查詢是否完成和取消任務等操作。所以AsyncTask構造函數中主要工作是:

  1. 在一個Callable對象mWorker的call方法中,調用doInBackground方法,并將結果傳給postResult方法
  2. 創建以mWorker作為參數的FutureTask對象mFuture。

接下來再看AsyncTask.execute()方法:

    @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:
                    //如果任務沒有結束mStatus狀態為RUNNING,則會拋出異常,所以每個AsyncTask在后臺任務執行完成前只能被執行一次,多次調用會引發異常
                    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;
    }

execute() 方法直接調用executeOnExecutor傳入默認的sDefaultExecutor,是串行Executor,executeOnExecutor()方法首先回調onPreExecute(),然后調用sDefaultExecutor.execute()執行構造函數中的Callable任務mWorker,下面看下sDefaultExecutor的定義:

    /**
     * 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 volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    private static class SerialExecutor implements Executor {
        //Runnable緩存隊列
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        //mActive正在執行的Runnable
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
                        //mFuture的run()方法會調用mWorker的call()方法
                        r.run();
                    } finally {
                        //執行完一個任務后再從緩存隊列中取下一個
                        scheduleNext();
                    }
                }
            });
            //第一次mActive為null,直接調用scheduleNext
            if (mActive == null) {
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                //真正在線程池中開始執行任務
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }

SerialExecutor主要作用請參考注釋,其實SerialExecutor的作用是保證來的線程是串行執行的,真正在后臺開始執行任務是THREAD_POOL_EXECUTOR.execute(mActive)

    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE_SECONDS = 30;

    //用于創建線程池總的線程
    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());
        }
    };
    //緩存隊列,用來存儲執行的任務,基于鏈表的先進先出隊列,這里指定長度為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;

    static {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                sPoolWorkQueue, sThreadFactory);
        //但是如果調用了allowCoreThreadTimeOut(boolean)方法,在線程池中的線程數不大于corePoolSize時,keepAliveTime參數也會起作用,直到線程池中的線程數為0;
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

java.uitl.concurrent.ThreadPoolExecutor類是線程池中最核心的一個類,這里創建ThreadPoolExecutor對象的幾個重要參數:

  • CORE_POOL_SIZE
    線程池中的核心線程個數,當線程池中線程數小于CORE_POOL_SIZE時,進來新任務就創建線程,當大于CORE_POOL_SIZE時,則放入緩存隊列中,這里定義為2到4個。
  • MAXIMUM_POOL_SIZE
    線程池中最大線程個數,當緩存隊列已滿或者任務劇增時,最多可以創建的線程個數,這里為 CPU_COUNT * 2 + 1
  • KEEP_ALIVE_SECONDS
    表示線程沒有任務執行時最多保持多久時間會終止。默認情況下,只有當線程池中的線程數大于corePoolSize時,keepAliveTime才會起作用,直到線程池中的線程數不大于corePoolSize,這里是30s
  • TimeUnit.SECONDS
    keepAliveTime的時間單位為s
  • sPoolWorkQueue
    線程池緩存隊列
  • sThreadFactory
    線程工廠,用來創建線程

回到前面構造函數中執行完后臺任務doInBackground,會調用postResult處理結果

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

這里getHandler()通常返回InternalHandler的靜態實例sHandler

    private static InternalHandler sHandler;
    private static class InternalHandler extends Handler {
        public InternalHandler(Looper looper) {
            super(looper);
        }

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

sHandler綁定的主線程的Looper,這就保證了onProgressUpdate和onPostExecute函數在主線程中回調

    private static Handler getMainHandler() {
        synchronized (AsyncTask.class) {
            if (sHandler == null) {
                sHandler = new InternalHandler(Looper.getMainLooper());
            }
            return sHandler;
        }
    }
  • 關于串行并行問題

    串行:

    直接調用execute方法使用默認的Executor: SERIAL_EXECUTOR,這是個靜態實例,所以適用于以下有多個任務的情況下,保證串行執行

    MyAsyncTask task1 = new MyAsyncTask();
    MyAsyncTask task2 = new MyAsyncTask();
    MyAsyncTask task3 = new MyAsyncTask();
    ... ...
    task1.execute();
    task2.execute();
    task3.execute();
    
    

    并行:

    如果希望并行執行任務則需要調用方法executeOnExecutor(),傳入參數Executor:THREAD_POOL_EXECUTOR

    MyAsyncTask task1 = new MyAsyncTask();
    MyAsyncTask task2 = new MyAsyncTask();
    MyAsyncTask task3 = new MyAsyncTask();
    ... ...
    task1.executeOnExecutor(THREAD_POOL_EXECUTOR,...);
    task2.executeOnExecutor(THREAD_POOL_EXECUTOR,...);
    task3.executeOnExecutor(THREAD_POOL_EXECUTOR,...);
    

三、參考文檔

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,224評論 6 529
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 97,916評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,014評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,466評論 1 308
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,245評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,795評論 1 320
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,869評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,010評論 0 285
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,524評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,487評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,634評論 1 366
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,173評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,884評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,282評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,541評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,236評論 3 388
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,623評論 2 370