Android--AsyncTask的串行和並行

轉載請註明出處:http://blog.csdn.net/singwhatiwanna/article/details/17596225

前言

什麼是AsyncTask,相信搞過android開發的朋友們都不陌生。AsyncTask內部封裝了Thread和Handler,可以讓我們在後臺進行計算並且把計算的結果及時更新到UI上,而這些正是Thread+Handler所做的事情,沒錯,AsyncTask的作用就是簡化Thread+Handler,讓我們能夠通過更少的代碼來完成一樣的功能,這裏,我要說明的是:AsyncTask只是簡化Thread+Handler而不是替代,實際上它也替代不了。同時,AsyncTask從最開始到現在已經經過了幾次代碼修改,任務的執行邏輯慢慢地發生了改變,並不是大家所想象的那樣:AsyncTask是完全並行執行的就像多個線程一樣,其實不是的,所以用AsyncTask的時候還是要注意,下面會一一說明。另外本文主要是分析AsyncTask的源代碼以及使用時候的一些注意事項,如果你還不熟悉AsyncTask,請先閱讀android之AsyncTask 來了解其基本用法。

這裏先給出AsyncTask的一個例子:

  1. private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {  
  2.      protected Long doInBackground(URL... urls) {  
  3.          int count = urls.length;  
  4.          long totalSize = 0;  
  5.          for (int i = 0; i < count; i++) {  
  6.              totalSize += Downloader.downloadFile(urls[i]);  
  7.              publishProgress((int) ((i / (float) count) * 100));  
  8.              // Escape early if cancel() is called  
  9.              if (isCancelled()) break;  
  10.          }  
  11.          return totalSize;  
  12.      }  
  13.   
  14.      protected void onProgressUpdate(Integer... progress) {  
  15.          setProgressPercent(progress[0]);  
  16.      }  
  17.   
  18.      protected void onPostExecute(Long result) {  
  19.          showDialog("Downloaded " + result + " bytes");  
  20.      }  
  21.  }  

使用AsyncTask的規則

  • AsyncTask的類必須在UI線程加載(從4.1開始系統會幫我們自動完成)
  • AsyncTask對象必須在UI線程創建
  • execute方法必須在UI線程調用
  • 不要在你的程序中去直接調用onPreExecute(), onPostExecute, doInBackground, onProgressUpdate方法
  • 一個AsyncTask對象只能執行一次,即只能調用一次execute方法,否則會報運行時異常
  • AsyncTask不是被設計爲處理耗時操作的,耗時上限爲幾秒鐘,如果要做長耗時操作,強烈建議你使用Executor,ThreadPoolExecutor以及FutureTask
  • 在1.6之前,AsyncTask是串行執行任務的,1.6的時候AsyncTask開始採用線程池裏處理並行任務,但是從3.0開始,爲了避免AsyncTask所帶來的併發錯誤,AsyncTask又採用一個線程來串行執行任務

AsyncTask到底是串行還是並行?

給大家做一下實驗,請看如下實驗代碼:代碼很簡單,就是點擊按鈕的時候同時執行5個AsyncTask,每個AsyncTask休眠3s,同時把每個AsyncTask執行結束的時間打印出來,這樣我們就能觀察出到底是串行執行還是並行執行。

  1. @Override  
  2. public void onClick(View v) {  
  3.     if (v == mButton) {  
  4.         new MyAsyncTask("AsyncTask#1").execute("");  
  5.         new MyAsyncTask("AsyncTask#2").execute("");  
  6.         new MyAsyncTask("AsyncTask#3").execute("");  
  7.         new MyAsyncTask("AsyncTask#4").execute("");  
  8.         new MyAsyncTask("AsyncTask#5").execute("");  
  9.     }  
  10.   
  11. }  
  12.   
  13. private static class MyAsyncTask extends AsyncTask<String, Integer, String> {  
  14.   
  15.     private String mName = "AsyncTask";  
  16.   
  17.     public MyAsyncTask(String name) {  
  18.         super();  
  19.         mName = name;  
  20.     }  
  21.   
  22.     @Override  
  23.     protected String doInBackground(String... params) {  
  24.         try {  
  25.             Thread.sleep(3000);  
  26.         } catch (InterruptedException e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.         return mName;  
  30.     }  
  31.   
  32.     @Override  
  33.     protected void onPostExecute(String result) {  
  34.         super.onPostExecute(result);  
  35.         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  36.         Log.e(TAG, result + "execute finish at " + df.format(new Date()));  
  37.     }  
  38. }  
我找了2個手機,系統分別是4.1.1和2.3.3,按照我前面的描述,AsyncTask在4.1.1應該是串行的,在2.3.3應該是並行的,到底是不是這樣呢?請看Log

Android 4.1.1上執行:從下面Log可以看出,5個AsyncTask共耗時15s且時間間隔爲3s,很顯然是串行執行的


Android 2.3.3上執行:從下面Log可以看出,5個AsyncTask的結束時間是一樣的,很顯然是並行執行


結論:從上面的兩個Log可以看出,我前面的描述是完全正確的。下面請看源碼,讓我們去了解下其中的原理。

源碼分析

  1. /* 
  2.  * Copyright (C) 2008 The Android Open Source Project 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16.   
  17. package android.os;  
  18.   
  19. import java.util.ArrayDeque;  
  20. import java.util.concurrent.BlockingQueue;  
  21. import java.util.concurrent.Callable;  
  22. import java.util.concurrent.CancellationException;  
  23. import java.util.concurrent.Executor;  
  24. import java.util.concurrent.ExecutionException;  
  25. import java.util.concurrent.FutureTask;  
  26. import java.util.concurrent.LinkedBlockingQueue;  
  27. import java.util.concurrent.ThreadFactory;  
  28. import java.util.concurrent.ThreadPoolExecutor;  
  29. import java.util.concurrent.TimeUnit;  
  30. import java.util.concurrent.TimeoutException;  
  31. import java.util.concurrent.atomic.AtomicBoolean;  
  32. import java.util.concurrent.atomic.AtomicInteger;  
  33.   
  34. public abstract class AsyncTask<Params, Progress, Result> {  
  35.     private static final String LOG_TAG = "AsyncTask";  
  36.   
  37.     //獲取當前的cpu核心數  
  38.     private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();  
  39.     //線程池核心容量  
  40.     private static final int CORE_POOL_SIZE = CPU_COUNT + 1;  
  41.     //線程池最大容量  
  42.     private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;  
  43.     //過剩的空閒線程的存活時間  
  44.     private static final int KEEP_ALIVE = 1;  
  45.     //ThreadFactory 線程工廠,通過工廠方法newThread來獲取新線程  
  46.     private static final ThreadFactory sThreadFactory = new ThreadFactory() {  
  47.         //原子整數,可以在超高併發下正常工作  
  48.         private final AtomicInteger mCount = new AtomicInteger(1);  
  49.   
  50.         public Thread newThread(Runnable r) {  
  51.             return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());  
  52.         }  
  53.     };  
  54.     //靜態阻塞式隊列,用來存放待執行的任務,初始容量:128個  
  55.     private static final BlockingQueue<Runnable> sPoolWorkQueue =  
  56.             new LinkedBlockingQueue<Runnable>(128);  
  57.   
  58.     /** 
  59.      * 靜態併發線程池,可以用來並行執行任務,儘管從3.0開始,AsyncTask默認是串行執行任務 
  60.      * 但是我們仍然能構造出並行的AsyncTask 
  61.      */  
  62.     public static final Executor THREAD_POOL_EXECUTOR  
  63.             = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,  
  64.                     TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);  
  65.   
  66.     /** 
  67.      * 靜態串行任務執行器,其內部實現了串行控制, 
  68.      * 循環的取出一個個任務交給上述的併發線程池去執行 
  69.      */  
  70.     public static final Executor SERIAL_EXECUTOR = new SerialExecutor();  
  71.     //消息類型:發送結果  
  72.     private static final int MESSAGE_POST_RESULT = 0x1;  
  73.     //消息類型:更新進度  
  74.     private static final int MESSAGE_POST_PROGRESS = 0x2;  
  75.     /**靜態Handler,用來發送上述兩種通知,採用UI線程的Looper來處理消息 
  76.      * 這就是爲什麼AsyncTask必須在UI線程調用,因爲子線程 
  77.      * 默認沒有Looper無法創建下面的Handler,程序會直接Crash 
  78.      */  
  79.     private static final InternalHandler sHandler = new InternalHandler();  
  80.     //默認任務執行器,被賦值爲串行任務執行器,就是它,AsyncTask變成串行的了  
  81.     private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;  
  82.     //如下兩個變量我們先不要深究,不影響我們對整體邏輯的理解  
  83.     private final WorkerRunnable<Params, Result> mWorker;  
  84.     private final FutureTask<Result> mFuture;  
  85.     //任務的狀態 默認爲掛起,即等待執行,其類型標識爲易變的(volatile)  
  86.     private volatile Status mStatus = Status.PENDING;  
  87.     //原子布爾型,支持高併發訪問,標識任務是否被取消  
  88.     private final AtomicBoolean mCancelled = new AtomicBoolean();  
  89.     //原子布爾型,支持高併發訪問,標識任務是否被執行過  
  90.     private final AtomicBoolean mTaskInvoked = new AtomicBoolean();  
  91.   
  92.     /*串行執行器的實現,我們要好好看看,它是怎麼把並行轉爲串行的 
  93.      *目前我們需要知道,asyncTask.execute(Params ...)實際上會調用 
  94.      *SerialExecutor的execute方法,這一點後面再說明。也就是說:當你的asyncTask執行的時候, 
  95.      *首先你的task會被加入到任務隊列,然後排隊,一個個執行 
  96.      */  
  97.     private static class SerialExecutor implements Executor {  
  98.         //線性雙向隊列,用來存儲所有的AsyncTask任務  
  99.         final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();  
  100.         //當前正在執行的AsyncTask任務  
  101.         Runnable mActive;  
  102.   
  103.         public synchronized void execute(final Runnable r) {  
  104.             //將新的AsyncTask任務加入到雙向隊列中  
  105.             mTasks.offer(new Runnable() {  
  106.                 public void run() {  
  107.                     try {  
  108.                         //執行AsyncTask任務  
  109.                         r.run();  
  110.                     } finally {  
  111.                         //當前AsyncTask任務執行完畢後,進行下一輪執行,如果還有未執行任務的話  
  112.                         //這一點很明顯體現了AsyncTask是串行執行任務的,總是一個任務執行完畢纔會執行下一個任務  
  113.                         scheduleNext();  
  114.                     }  
  115.                 }  
  116.             });  
  117.             //如果當前沒有任務在執行,直接進入執行邏輯  
  118.             if (mActive == null) {  
  119.                 scheduleNext();  
  120.             }  
  121.         }  
  122.   
  123.         protected synchronized void scheduleNext() {  
  124.             //從任務隊列中取出隊列頭部的任務,如果有就交給併發線程池去執行  
  125.             if ((mActive = mTasks.poll()) != null) {  
  126.                 THREAD_POOL_EXECUTOR.execute(mActive);  
  127.             }  
  128.         }  
  129.     }  
  130.   
  131.     /** 
  132.      * 任務的三種狀態 
  133.      */  
  134.     public enum Status {  
  135.         /** 
  136.          * 任務等待執行 
  137.          */  
  138.         PENDING,  
  139.         /** 
  140.          * 任務正在執行 
  141.          */  
  142.         RUNNING,  
  143.         /** 
  144.          * 任務已經執行結束 
  145.          */  
  146.         FINISHED,  
  147.     }  
  148.   
  149.     /** 隱藏API:在UI線程中調用,用來初始化Handler */  
  150.     public static void init() {  
  151.         sHandler.getLooper();  
  152.     }  
  153.   
  154.     /** 隱藏API:爲AsyncTask設置默認執行器 */  
  155.     public static void setDefaultExecutor(Executor exec) {  
  156.         sDefaultExecutor = exec;  
  157.     }  
  158.   
  159.     /** 
  160.      * Creates a new asynchronous task. This constructor must be invoked on the UI thread. 
  161.      */  
  162.     public AsyncTask() {  
  163.         mWorker = new WorkerRunnable<Params, Result>() {  
  164.             public Result call() throws Exception {  
  165.                 mTaskInvoked.set(true);  
  166.   
  167.                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  
  168.                 //noinspection unchecked  
  169.                 return postResult(doInBackground(mParams));  
  170.             }  
  171.         };  
  172.   
  173.         mFuture = new FutureTask<Result>(mWorker) {  
  174.             @Override  
  175.             protected void done() {  
  176.                 try {  
  177.                     postResultIfNotInvoked(get());  
  178.                 } catch (InterruptedException e) {  
  179.                     android.util.Log.w(LOG_TAG, e);  
  180.                 } catch (ExecutionException e) {  
  181.                     throw new RuntimeException("An error occured while executing doInBackground()",  
  182.                             e.getCause());  
  183.                 } catch (CancellationException e) {  
  184.                     postResultIfNotInvoked(null);  
  185.                 }  
  186.             }  
  187.         };  
  188.     }  
  189.   
  190.     private void postResultIfNotInvoked(Result result) {  
  191.         final boolean wasTaskInvoked = mTaskInvoked.get();  
  192.         if (!wasTaskInvoked) {  
  193.             postResult(result);  
  194.         }  
  195.     }  
  196.     //doInBackground執行完畢,發送消息  
  197.     private Result postResult(Result result) {  
  198.         @SuppressWarnings("unchecked")  
  199.         Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,  
  200.                 new AsyncTaskResult<Result>(this, result));  
  201.         message.sendToTarget();  
  202.         return result;  
  203.     }  
  204.   
  205.     /** 
  206.      * 返回任務的狀態 
  207.      */  
  208.     public final Status getStatus() {  
  209.         return mStatus;  
  210.     }  
  211.   
  212.     /** 
  213.      * 這個方法是我們必須要重寫的,用來做後臺計算 
  214.      * 所在線程:後臺線程 
  215.      */  
  216.     protected abstract Result doInBackground(Params... params);  
  217.   
  218.     /** 
  219.      * 在doInBackground之前調用,用來做初始化工作 
  220.      * 所在線程:UI線程 
  221.      */  
  222.     protected void onPreExecute() {  
  223.     }  
  224.   
  225.     /** 
  226.      * 在doInBackground之後調用,用來接受後臺計算結果更新UI 
  227.      * 所在線程:UI線程 
  228.      */  
  229.     protected void onPostExecute(Result result) {  
  230.     }  
  231.   
  232.     /** 
  233.      * Runs on the UI thread after {@link #publishProgress} is invoked. 
  234.      /** 
  235.      * 在publishProgress之後調用,用來更新計算進度 
  236.      * 所在線程:UI線程 
  237.      */  
  238.     protected void onProgressUpdate(Progress... values) {  
  239.     }  
  240.   
  241.      /** 
  242.      * cancel被調用並且doInBackground執行結束,會調用onCancelled,表示任務被取消 
  243.      * 這個時候onPostExecute不會再被調用,二者是互斥的,分別表示任務取消和任務執行完成 
  244.      * 所在線程:UI線程 
  245.      */  
  246.     @SuppressWarnings({"UnusedParameters"})  
  247.     protected void onCancelled(Result result) {  
  248.         onCancelled();  
  249.     }      
  250.       
  251.     protected void onCancelled() {  
  252.     }  
  253.   
  254.     public final boolean isCancelled() {  
  255.         return mCancelled.get();  
  256.     }  
  257.   
  258.     public final boolean cancel(boolean mayInterruptIfRunning) {  
  259.         mCancelled.set(true);  
  260.         return mFuture.cancel(mayInterruptIfRunning);  
  261.     }  
  262.   
  263.     public final Result get() throws InterruptedException, ExecutionException {  
  264.         return mFuture.get();  
  265.     }  
  266.   
  267.     public final Result get(long timeout, TimeUnit unit) throws InterruptedException,  
  268.             ExecutionException, TimeoutException {  
  269.         return mFuture.get(timeout, unit);  
  270.     }  
  271.   
  272.     /** 
  273.      * 這個方法如何執行和系統版本有關,在AsyncTask的使用規則裏已經說明,如果你真的想使用並行AsyncTask, 
  274.      * 也是可以的,只要稍作修改 
  275.      * 必須在UI線程調用此方法 
  276.      */  
  277.     public final AsyncTask<Params, Progress, Result> execute(Params... params) {  
  278.         //串行執行  
  279.         return executeOnExecutor(sDefaultExecutor, params);  
  280.         //如果我們想並行執行,這樣改就行了,當然這個方法我們沒法改  
  281.         //return executeOnExecutor(THREAD_POOL_EXECUTOR, params);  
  282.     }  
  283.   
  284.     /** 
  285.      * 通過這個方法我們可以自定義AsyncTask的執行方式,串行or並行,甚至可以採用自己的Executor 
  286.      * 爲了實現並行,我們可以在外部這麼用AsyncTask: 
  287.      * asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Params... params); 
  288.      * 必須在UI線程調用此方法 
  289.      */  
  290.     public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,  
  291.             Params... params) {  
  292.         if (mStatus != Status.PENDING) {  
  293.             switch (mStatus) {  
  294.                 case RUNNING:  
  295.                     throw new IllegalStateException("Cannot execute task:"  
  296.                             + " the task is already running.");  
  297.                 case FINISHED:  
  298.                     throw new IllegalStateException("Cannot execute task:"  
  299.                             + " the task has already been executed "  
  300.                             + "(a task can be executed only once)");  
  301.             }  
  302.         }  
  303.   
  304.         mStatus = Status.RUNNING;  
  305.         //這裏#onPreExecute會最先執行  
  306.         onPreExecute();  
  307.   
  308.         mWorker.mParams = params;  
  309.         //然後後臺計算#doInBackground才真正開始  
  310.         exec.execute(mFuture);  
  311.         //接着會有#onProgressUpdate被調用,最後是#onPostExecute  
  312.   
  313.         return this;  
  314.     }  
  315.   
  316.     /** 
  317.      * 這是AsyncTask提供的一個靜態方法,方便我們直接執行一個runnable 
  318.      */  
  319.     public static void execute(Runnable runnable) {  
  320.         sDefaultExecutor.execute(runnable);  
  321.     }  
  322.   
  323.     /** 
  324.      * 打印後臺計算進度,onProgressUpdate會被調用 
  325.      */  
  326.     protected final void publishProgress(Progress... values) {  
  327.         if (!isCancelled()) {  
  328.             sHandler.obtainMessage(MESSAGE_POST_PROGRESS,  
  329.                     new AsyncTaskResult<Progress>(this, values)).sendToTarget();  
  330.         }  
  331.     }  
  332.   
  333.     //任務結束的時候會進行判斷,如果任務沒有被取消,則onPostExecute會被調用  
  334.     private void finish(Result result) {  
  335.         if (isCancelled()) {  
  336.             onCancelled(result);  
  337.         } else {  
  338.             onPostExecute(result);  
  339.         }  
  340.         mStatus = Status.FINISHED;  
  341.     }  
  342.   
  343.     //AsyncTask內部Handler,用來發送後臺計算進度更新消息和計算完成消息  
  344.     private static class InternalHandler extends Handler {  
  345.         @SuppressWarnings({"unchecked""RawUseOfParameterizedType"})  
  346.         @Override  
  347.         public void handleMessage(Message msg) {  
  348.             AsyncTaskResult result = (AsyncTaskResult) msg.obj;  
  349.             switch (msg.what) {  
  350.                 case MESSAGE_POST_RESULT:  
  351.                     // There is only one result  
  352.                     result.mTask.finish(result.mData[0]);  
  353.                     break;  
  354.                 case MESSAGE_POST_PROGRESS:  
  355.                     result.mTask.onProgressUpdate(result.mData);  
  356.                     break;  
  357.             }  
  358.         }  
  359.     }  
  360.   
  361.     private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {  
  362.         Params[] mParams;  
  363.     }  
  364.   
  365.     @SuppressWarnings({"RawUseOfParameterizedType"})  
  366.     private static class AsyncTaskResult<Data> {  
  367.         final AsyncTask mTask;  
  368.         final Data[] mData;  
  369.   
  370.         AsyncTaskResult(AsyncTask task, Data... data) {  
  371.             mTask = task;  
  372.             mData = data;  
  373.         }  
  374.     }  
  375. }  

讓你的AsyncTask在3.0以上的系統中並行起來

通過上面的源碼分析,我已經給出了在3.0以上系統中讓AsyncTask並行執行的方法,現在,讓我們來試一試,代碼還是之前採用的測試代碼,我們要稍作修改,調用AsyncTask的executeOnExecutor方法而不是execute,請看:

  1. @TargetApi(Build.VERSION_CODES.HONEYCOMB)  
  2. @Override  
  3. public void onClick(View v) {  
  4.     if (v == mButton) {  
  5.         new MyAsyncTask("AsyncTask#1").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");  
  6.         new MyAsyncTask("AsyncTask#2").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");  
  7.         new MyAsyncTask("AsyncTask#3").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");  
  8.         new MyAsyncTask("AsyncTask#4").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");  
  9.         new MyAsyncTask("AsyncTask#5").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");  
  10.     }  
  11.   
  12. }  
  13.   
  14. private static class MyAsyncTask extends AsyncTask<String, Integer, String> {  
  15.   
  16.     private String mName = "AsyncTask";  
  17.   
  18.     public MyAsyncTask(String name) {  
  19.         super();  
  20.         mName = name;  
  21.     }  
  22.   
  23.     @Override  
  24.     protected String doInBackground(String... params) {  
  25.         try {  
  26.             Thread.sleep(3000);  
  27.         } catch (InterruptedException e) {  
  28.             e.printStackTrace();  
  29.         }  
  30.         return mName;  
  31.     }  
  32.   
  33.     @Override  
  34.     protected void onPostExecute(String result) {  
  35.         super.onPostExecute(result);  
  36.         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  37.         Log.e(TAG, result + "execute finish at " + df.format(new Date()));  
  38.     }  
  39. }  
下面是系統爲4.1.1手機打印出的Log:很顯然,我們的目的達到了,成功的讓AsyncTask在4.1.1的手機上並行起來了,很高興吧!希望這篇文章對你有用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章