在Android中实现异步任务机制有两种方式,Handler 和 AsyncTask      Handler模式需要为每一个任务创建一个新的线程,任务完成后通过Handler实例向UI线程发送消息,完成界面的更新,这种方式对于整个过程的控制比较精细,但也是有缺点的,例如代码相对臃肿,在多个任务同时执行时,不易对线程进行精确的控制。 为了简化操作,Android1.5提供了工具类android.os.AsyncTask,它使创建异步任务变得更加简单,不再需要编写任务线程和Handler实例即可完成相同的任务,但其内部也是使用Handler来传递消息,而且基于线程池。因此明显的AsyncTask比Handler要重量级。 先来看看AsyncTask的定义:
[java]  view plain copy print ?
  1. public abstract class AsyncTask {  }  

三种泛型类型分别代表: 1.“启动任务执行的输入参数”、 2.“后台任务执行的进度”、 3.“后台计算结果的类型”
注: 在特定场合下,并不是所有类型都被使用,如果没有被使用,可以用java.lang.Void类型代替。
一个异步任务的执行一般包括以下几个步骤: 1. execute(Params... params),执行一个异步任务,需要我们在代码中调用此方法,触发异步任务的执行。
2. onPreExecute(),在execute(Params... params)被调用后立即执行,一般用来在执行后台任务前对UI做一些标记。
3. doInBackground(Params... params),在onPreExecute()完成后立即执行,用于执行较为费时的操作,此方法将接收输入参数和返回计算结果。在执行过程中可以调用publishProgress(Progress... values)来更新进度信息。
4. onProgressUpdate(Progress... values),在调用publishProgress(Progress... values)时,此方法被执行,直接将进度信息更新到UI组件上。
5. onPostExecute(Result result),当后台操作结束时,此方法将会被调用,计算结果将做为参数传递到此方法中,直接将结果显示到UI组件上。
在使用的时候,有几点需要格外注意: 1. 异步任务的实例必须在UI线程中创建。 2. execute(Params... params)方法必须在UI线程中调用。 3. 不能在doInBackground(Params... params)中更改UI组件的信息。 4. 一个任务实例只能执行一次,如果执行第二次将会抛出异常。

一 、 AsyncTask的使用示例

接下来,我们来看看如何使用AsyncTask执行异步任务操作,我们先建立一个项目,结构如下:
结构相对简单一些,让我们先看看MainActivity.java的代码: [java]  view plain copy print ?
  1. package com.scott.async;    
  2.     
  3. import java.io.ByteArrayOutputStream;    
  4. import java.io.InputStream;    
  5.     
  6. import org.apache.http.HttpEntity;    
  7. import org.apache.http.HttpResponse;    
  8. import org.apache.http.HttpStatus;    
  9. import org.apache.http.client.HttpClient;    
  10. import org.apache.http.client.methods.HttpGet;    
  11. import org.apache.http.impl.client.DefaultHttpClient;    
  12.     
  13. import android.app.Activity;    
  14. import android.os.AsyncTask;    
  15. import android.os.Bundle;    
  16. import android.util.Log;    
  17. import android.view.View;    
  18. import android.widget.Button;    
  19. import android.widget.ProgressBar;    
  20. import android.widget.TextView;    
  21.     
  22. public class MainActivity extends Activity {    
  23.         
  24.     private static final String TAG = "ASYNC_TASK";    
  25.         
  26.     private Button execute;    
  27.     private Button cancel;    
  28.     private ProgressBar progressBar;    
  29.     private TextView textView;    
  30.         
  31.     private MyTask mTask;    
  32.         
  33.     @Override    
  34.     public void onCreate(Bundle savedInstanceState) {    
  35.         super.onCreate(savedInstanceState);    
  36.         setContentView(R.layout.main);    
  37.             
  38.         execute = (Button) findViewById(R.id.execute);    
  39.         execute.setOnClickListener(new View.OnClickListener() {    
  40.             @Override    
  41.             public void onClick(View v) {    
  42.                 // 注意每次需new一个实例,新建的任务只能执行一次,否则会出现异常    
  43.                 mTask = new MyTask();    
  44.                 mTask.execute("http://www.baidu.com");    
  45.                     
  46.                 execute.setEnabled(false);    
  47.                 cancel.setEnabled(true);    
  48.             }    
  49.         });    
  50.         cancel = (Button) findViewById(R.id.cancel);    
  51.         cancel.setOnClickListener(new View.OnClickListener() {    
  52.             @Override    
  53.             public void onClick(View v) {    
  54.                 //取消一个正在执行的任务,onCancelled方法将会被调用,实际上是调用了FutureTask的取消操作,关于FutureTask下文会有介绍    
  55.                 mTask.cancel(true);    
  56.             }    
  57.         });    
  58.         progressBar = (ProgressBar) findViewById(R.id.progress_bar);    
  59.         textView = (TextView) findViewById(R.id.text_view);    
  60.             
  61.     }    
  62.         
  63.     private class MyTask extends AsyncTask {    
  64.         //onPreExecute方法用于在执行后台任务前做一些UI操作    
  65.         @Override    
  66.         protected void onPreExecute() {    
  67.             Log.i(TAG, "onPreExecute() called");    
  68.             textView.setText("loading...");    
  69.         }    
  70.             
  71.         // doInBackground方法内部执行后台任务,不可在此方法内修改UI,运行在后台线程。  
  72.         @Override    
  73.         protected String doInBackground(String... params) {    
  74.             Log.i(TAG, "doInBackground(Params... params) called");    
  75.             try {    
  76.                 HttpClient client = new DefaultHttpClient();    
  77.                 HttpGet get = new HttpGet(params[0]);    
  78.                 HttpResponse response = client.execute(get);    
  79.                 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {    
  80.                     HttpEntity entity = response.getEntity();    
  81.                     InputStream is = entity.getContent();    
  82.                     long total = entity.getContentLength();    
  83.                     ByteArrayOutputStream baos = new ByteArrayOutputStream();    
  84.                     byte[] buf = new byte[1024];    
  85.                     int count = 0;    
  86.                     int length = -1;    
  87.                     while ((length = is.read(buf)) != -1) {    
  88.                         baos.write(buf, 0, length);    
  89.                         count += length;    
  90.                         //调用publishProgress公布进度,最后onProgressUpdate方法将被执行    
  91.                         publishProgress((int) ((count / (float) total) * 100));    
  92.                         //为了演示进度,休眠500毫秒    
  93.                         Thread.sleep(500);    
  94.                     }    
  95.                     return new String(baos.toByteArray(), "gb2312");    
  96.                 }    
  97.             } catch (Exception e) {    
  98.                 Log.e(TAG, e.getMessage());    
  99.             }    
  100.             return null;    
  101.         }    
  102.             
  103.         // onProgressUpdate方法用于更新进度信息    
  104.         @Override    
  105.         protected void onProgressUpdate(Integer... progresses) {    
  106.             Log.i(TAG, "onProgressUpdate(Progress... progresses) called");    
  107.             progressBar.setProgress(progresses[0]);    
  108.             textView.setText("loading..." + progresses[0] + "%");    
  109.         }    
  110.             
  111.         // onPostExecute方法用于在执行完后台任务后更新UI,显示结果。 运行在UI线程    
  112.         @Override    
  113.         protected void onPostExecute(String result) {    
  114.             Log.i(TAG, "onPostExecute(Result result) called");    
  115.             textView.setText(result);    
  116.                 
  117.             execute.setEnabled(true);    
  118.             cancel.setEnabled(false);    
  119.         }    
  120.             
  121.         //onCancelled方法用于在取消执行中的任务时更改UI    
  122.         @Override    
  123.         protected void onCancelled() {    
  124.             Log.i(TAG, "onCancelled() called");    
  125.             textView.setText("cancelled");    
  126.             progressBar.setProgress(0);    
  127.                 
  128.             execute.setEnabled(true);    
  129.             cancel.setEnabled(false);    
  130.         }    
  131.     }    
  132. }    



布局文件main.xml代码如下: [html]  view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     android:orientation="vertical"    
  4.     android:layout_width="fill_parent"    
  5.     android:layout_height="fill_parent">    
  6.     <Button    
  7.         android:id="@+id/execute"    
  8.         android:layout_width="fill_parent"    
  9.         android:layout_height="wrap_content"    
  10.         android:text="execute"/>    
  11.     <Button    
  12.         android:id="@+id/cancel"    
  13.         android:layout_width="fill_parent"    
  14.         android:layout_height="wrap_content"    
  15.         android:enabled="false"    
  16.         android:text="cancel"/>    
  17.     <ProgressBar     
  18.         android:id="@+id/progress_bar"     
  19.         android:layout_width="fill_parent"     
  20.         android:layout_height="wrap_content"     
  21.         android:progress="0"    
  22.         android:max="100"    
  23.         style="?android:attr/progressBarStyleHorizontal"/>    
  24.     <ScrollView    
  25.         android:layout_width="fill_parent"     
  26.         android:layout_height="wrap_content">    
  27.         <TextView    
  28.             android:id="@+id/text_view"    
  29.             android:layout_width="fill_parent"     
  30.             android:layout_height="wrap_content"/>    
  31.     ScrollView>    
  32. LinearLayout>    

因为需要访问网络,所以我们还需要在AndroidManifest.xml中加入访问网络的权限: [html]  view plain copy print ?
  1. <uses-permission android:name="android.permission.INTERNET"/>  


二、 AsyncTask的实现基本原理

      上面介绍了AsyncTask的基本应用,有些朋友也许会有疑惑,AsyncTask内部是怎么执行的呢,它执行的过程跟我们使用Handler又有什么区别呢?答案是:AsyncTask是对Thread+Handler良好的封装,在android.os.AsyncTask代码里仍然可以看到Thread和Handler的踪迹。下面就向大家详细介绍一下AsyncTask的执行原理。
源代码如下 : [java]  view plain copy print ?
  1. /**  
  2.     * Override this method to perform a computation on a background thread. The  
  3.     * specified parameters are the parameters passed to {@link #execute}  
  4.     * by the caller of this task.  
  5.     *  
  6.     * This method can call {@link #publishProgress} to publish updates  
  7.     * on the UI thread.  
  8.     *  
  9.     * @param params The parameters of the task.  
  10.     *  
  11.     * @return A result, defined by the subclass of this task.  
  12.     *  这是一个abstract 方法,因此必须覆写。  
  13.     * @see #onPreExecute()  
  14.     * @see #onPostExecute  
  15.     * @see #publishProgress  
  16.     */    
  17.    protected abstract Result doInBackground(Params... params);    
  18.     
  19.    /**  
  20.     * Runs on the UI thread before {@link #doInBackground}.   
  21.     *  
  22.     * @see #onPostExecute  
  23.     * @see #doInBackground  
  24.     */    
  25.    protected void onPreExecute() {    
  26.    }    
  27.     
  28.    /**  
  29.     * Runs on the UI thread after {@link #doInBackground}. The  
  30.     * specified result is the value returned by {@link #doInBackground}  
  31.     * or null if the task was cancelled or an exception occured.  
  32.     *后台操作执行完后会调用的方法,在此更新UI。  
  33.     * @param result The result of the operation computed by {@link #doInBackground}.  
  34.     *  
  35.     * @see #onPreExecute  
  36.     * @see #doInBackground  
  37.     */    
  38.    @SuppressWarnings({"UnusedDeclaration"})    
  39.    protected void onPostExecute(Result result) {    
  40.    }    
  41.     
  42.    /**  
  43.     * Runs on the UI thread after {@link #publishProgress} is invoked.  
  44.     * The specified values are the values passed to {@link #publishProgress}.  
  45.     *  
  46.     * @param values The values indicating progress.  
  47.     * 传值更新进度条  
  48.     * @see #publishProgress  
  49.     * @see #doInBackground  
  50.     */    
  51.    @SuppressWarnings({"UnusedDeclaration"})    
  52.    protected void onProgressUpdate(Progress... values) {    
  53.    }    
  54.     
  55.   /**  
  56.     * Executes the task with the specified parameters. The task returns  
  57.     * itself (this) so that the caller can keep a reference to it.  
  58.     *  
  59.     * This method must be invoked on the UI thread.   注意execute方法必须在UI线程中调用  
  60.     *  
  61.     * @param params The parameters of the task.  
  62.     *  
  63.     * @return This instance of AsyncTask.  
  64.     *  
  65.     * @throws IllegalStateException If {@link #getStatus()} returns either  
  66.     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.  
  67.     */    
  68.    public final AsyncTask execute(Params... params) {    
  69.        if (mStatus != Status.PENDING) {    
  70.     // 状态检测,只有在PENDING状态下才能正常运行,构造抛出异常    
  71.            switch (mStatus) {    
  72.                case RUNNING:    
  73.                    throw new IllegalStateException("Cannot execute task:"    
  74.                            + " the task is already running.");    
  75.                case FINISHED:    
  76.                    throw new IllegalStateException("Cannot execute task:"    
  77.                            + " the task has already been executed "    
  78.                            + "(a task can be executed only once)");    
  79.            }    
  80.        }    
  81.     
  82.        mStatus = Status.RUNNING;    
  83. // 正在执行任务前的准备处理    
  84.        onPreExecute();    
  85. // 获得从UI现存传递来的参数    
  86.        mWorker.mParams = params;    
  87. // 交给线程池管理器进行调度,参数为FutureTask类型,构造mFuture时mWorker被传递了进去,后边会继续分析    
  88.        sExecutor.execute(mFuture);    
  89. // 返回自身,使得调用者可以保持一个引用    
  90.        return this;    
  91.    }    
  92.     
  93.    /**  
  94.     * This method can be invoked from {@link #doInBackground} to  
  95.     * publish updates on the UI thread while the background computation is  
  96.     * still running. Each call to this method will trigger the execution of  
  97.     * {@link #onProgressUpdate} on the UI thread.  
  98.     *  
  99.     * @param values The progress values to update the UI with.  
  100.     *  
  101.     * @see #onProgressUpdate  
  102.     * @see #doInBackground  
  103.     */    
  104.    protected final void publishProgress(Progress... values) {    
  105.        sHandler.obtainMessage(MESSAGE_POST_PROGRESS,    
  106.                new AsyncTaskResult(this, values)).sendToTarget();    
  107.    }    



我们可以看到关键几个步骤的方法都在其中。 1、 doInBackground(Params... params)  是一个抽象方法,我们继承AsyncTask时必须覆写此方法; 2、 onPreExecute()、onProgressUpdate(Progress... values)、onPostExecute(Result result)、onCancelled() 这几个方法体都是空的,我们需要的时候可以选择性的覆写它们; 3、 publishProgress(Progress... values) 是final修饰的,不能覆写,只能去调用,我们一般会在doInBackground(Params... params)中调用此方法来更新进度条; 4、另外,我们可以看到有一个Status的枚举类和getStatus()方法,Status枚举类代码段如下: [java]  view plain copy print ?
  1. //初始状态    
  2.     private volatile Status mStatus = Status.PENDING;    
  3.     public enum Status {    
  4.         /**  
  5.          * Indicates that the task has not been executed yet.  
  6.          */    
  7.         PENDING,    
  8.         /**  
  9.          * Indicates that the task is running.  
  10.          */    
  11.         RUNNING,    
  12.         /**  
  13.          * Indicates that {@link AsyncTask#onPostExecute} has finished.  
  14.          */    
  15.         FINISHED,    
  16.     }    
  17.     
  18. /**  
  19.      * Returns the current status of this task.  
  20.      *  
  21.      * @return The current status.  
  22.      */    
  23.     public final Status getStatus() {    
  24.         return mStatus;    
  25.     }    

可以看到,AsyncTask的初始状态为 PENDING ,代表待定状态, RUNNING 代表执行状态, FINISHED 代表结束状态,这几种状态在AsyncTask一次生命周期内的很多地方被使用,非常重要。
在execute函数中涉及到三个陌生的变量:mWorker、sExecutor、mFuture,我们也会看一下: 关于sExecutor,它是java.util.concurrent.ThreadPoolExecutor的实例,用于管理线程的执行。代码如下: [java]  view plain copy print ?
  1. private static final int CORE_POOL_SIZE = 5;    
  2.    private static final int MAXIMUM_POOL_SIZE = 128;    
  3.    private static final int KEEP_ALIVE = 10;    
  4.     
  5. //新建一个队列用来存放线程    
  6.    private static final BlockingQueue sWorkQueue =    
  7.            new LinkedBlockingQueue(10);    
  8. //新建一个线程工厂    
  9.    private static final ThreadFactory sThreadFactory = new ThreadFactory() {    
  10.        private final AtomicInteger mCount = new AtomicInteger(1);    
  11.     //新建一个线程    
  12.        public Thread newThread(Runnable r) {    
  13.            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());    
  14.        }    
  15.    };    
  16. //新建一个线程池执行器,用于管理线程的执行    
  17.    private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,    
  18.            MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);    
  19. mWorker实际上是AsyncTask的一个的抽象内部类的实现对象实例,它实现了Callable接口中的call()方法,代码如下:  
  20. [java] view plaincopy  
  21. private static abstract class WorkerRunnable implements Callable {    
  22.         Params[] mParams;    
  23.     }    

而mFuture实际上是  java.util.concurrent.FutureTask  的实例,下面是它的FutureTask类的相关信息: [java]  view plain copy print ?
  1. /**  
  2.  * A cancellable asynchronous computation.  
  3.  * ...  
  4.  */    
  5. public class FutureTask implements RunnableFuture {    
  6.   
  7. public interface RunnableFuture extends Runnable, Future {    
  8.     /**  
  9.      * Sets this Future to the result of its computation  
  10.      * unless it has been cancelled.  
  11.      */    
  12.     void run();    
  13. }    

可以看到FutureTask是一个可以中途取消的用于异步计算的类。 下面是mWorker和mFuture实例在AsyncTask中的体现: [java]  view plain copy print ?
  1. private final WorkerRunnable mWorker;      
  2.    private final FutureTask mFuture;      
  3.       
  4. public AsyncTask() {      
  5.        mWorker = new WorkerRunnable() {      
  6.            //call方法被调用后,将设置优先级为后台级别, 然后调用AsyncTask的doInBackground方法      
  7.         public Result call() throws Exception {      
  8.                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);      
  9.                return doInBackground(mParams);      
  10.            }      
  11.        };      
  12.       
  13.     // 在mFuture实例中,将会调用mWorker做后台任务,完成后会调用done方法。    
  14.     // 这里将mWorker作为参数传递给了mFuture对象     
  15.        mFuture = new FutureTask(mWorker) {      
  16.            @Override      
  17.            protected void done() {      
  18.                Message message;      
  19.                Result result = null;      
  20.       
  21.                try {      
  22.                    result = get();      
  23.                } catch (InterruptedException e) {      
  24.                    android.util.Log.w(LOG_TAG, e);      
  25.                } catch (ExecutionException e) {      
  26.                    throw new RuntimeException("An error occured while executing doInBackground()",      
  27.                            e.getCause());      
  28.                } catch (CancellationException e) {      
  29.                 //发送取消任务的消息      
  30.                    message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,      
  31.                            new AsyncTaskResult(AsyncTask.this, (Result[]) null));      
  32.                    message.sendToTarget();      
  33.                    return;      
  34.                } catch (Throwable t) {      
  35.                    throw new RuntimeException("An error occured while executing "      
  36.                            + "doInBackground()", t);      
  37.                }      
  38.       
  39.             //发送显示结果的消息      
  40.                message = sHandler.obtainMessage(MESSAGE_POST_RESULT,      
  41.                        new AsyncTaskResult(AsyncTask.this, result));      
  42.                message.sendToTarget();      
  43.            }      
  44.        };      
  45.    }      


  我们看到上面的代码中,mFuture实例对象的done()方法中,如果捕捉到了CancellationException类型的异常,则发送一条“MESSAGE_POST_CANCEL”的消息;如果顺利执行,则发送一条“MESSAGE_POST_RESULT”的消息,而消息都与一个sHandler对象关联。 我们继续按着执行流程跟踪代码, [java]  view plain copy print ?
  1. // 正在执行任务前的准备处理    
  2.        onPreExecute();    
  3. // 获得从UI现存传递来的参数    
  4.        mWorker.mParams = params;    
  5. // 交给线程池管理器进行调度,参数为FutureTask类型,构造mFuture时mWorker被传递了进去,后边会继续分析    
  6.        sExecutor.execute(mFuture);    
  7. 进入到ThreadPoolExecutor的execute函数,如下 :  
  8. [java] view plaincopy  
  9. public void execute(Runnable command) {    
  10.      if (command == null)    
  11.          throw new NullPointerException();    
  12.      /*  
  13.       * Proceed in 3 steps:  
  14.       *  
  15.       * 1. If fewer than corePoolSize threads are running, try to  
  16.       * start a new thread with the given command as its first  
  17.       * task.  The call to addWorker atomically checks runState and  
  18.       * workerCount, and so prevents false alarms that would add  
  19.       * threads when it shouldn't, by returning false.  
  20.       *  
  21.       * 2. If a task can be successfully queued, then we still need  
  22.       * to double-check whether we should have added a thread  
  23.       * (because existing ones died since last checking) or that  
  24.       * the pool shut down since entry into this method. So we  
  25.       * recheck state and if necessary roll back the enqueuing if  
  26.       * stopped, or start a new thread if there are none.  
  27.       *  
  28.       * 3. If we cannot queue task, then we try to add a new  
  29.       * thread.  If it fails, we know we are shut down or saturated  
  30.       * and so reject the task.  
  31.       */    
  32.      int c = ctl.get();    
  33.      if (workerCountOf(c) < corePoolSize) {    
  34.          if (addWorker(command, true))    
  35.              return;    
  36.          c = ctl.get();    
  37.      }    
  38.      if (isRunning(c) && workQueue.offer(command)) {    
  39.          int recheck = ctl.get();    
  40.          if (! isRunning(recheck) && remove(command))    
  41.              reject(command);    
  42.          else if (workerCountOf(recheck) == 0)    
  43.              addWorker(nullfalse);    
  44.      }    
  45.      else if (!addWorker(command, false))    
  46.          reject(command);    
  47.  }    


可以看到,这段代码的主要功能是将异步任务mFuture加入到将要执行的队列中,重要的函数为addWoker,我们继续跟踪代码到该函数。 [java]  view plain copy print ?
  1. private boolean addWorker(Runnable firstTask, boolean core) {    
  2.         retry:    
  3.         for (;;) {    
  4.             int c = ctl.get();    
  5.             int rs = runStateOf(c);    
  6.     
  7.             // Check if queue empty only if necessary.    
  8.             if (rs >= SHUTDOWN &&    
  9.                 ! (rs == SHUTDOWN &&    
  10.                    firstTask == null &&    
  11.                    ! workQueue.isEmpty()))    
  12.                 return false;    
  13.     
  14.             for (;;) {    
  15.                 int wc = workerCountOf(c);    
  16.                 if (wc >= CAPACITY ||    
  17.                     wc >= (core ? corePoolSize : maximumPoolSize))    
  18.                     return false;    
  19.                 if (compareAndIncrementWorkerCount(c))    
  20.                     break retry;    
  21.                 c = ctl.get();  // Re-read ctl    
  22.                 if (runStateOf(c) != rs)    
  23.                     continue retry;    
  24.                 // else CAS failed due to workerCount change; retry inner loop    
  25.             }    
  26.         }    
  27.         
  28.     // 这里又生成了一个Worker的对象,将异步任务传递给了w    
  29.         Worker w = new Worker(firstTask);    
  30.         Thread t = w.thread;    
  31.     ......      // 后续代码省略    
  32.     wokers.add( w );// 将w添加到了wokers里,这是一个HashSet集合对象    
  33.     ......    
  34.     w.start();  // 启动该异步任务,即启动了mFuture任务。    
  35.     ......    
  36.         return true;    
  37.     }    


由于mFuture是FutureTask类型,因此继续跟踪到FutureTask的代码。可以看到该构造函数,即上文中构造mFuture时用的构造函数,参数我们传递的是mWorker。 [java]  view plain copy print ?
  1. public FutureTask(Callable callable) {    
  2.     if (callable == null)    
  3.         throw new NullPointerException();    
  4.     sync = new Sync(callable);    
  5. }    

可以看到构造函数又将mWorker交给了Sync类型。
而启动mFuture时就会执行其中的run函数,如下 :  [java]  view plain copy print ?
  1. public void run() {    
  2.       sync.innerRun();    
  3.   }   

可知,实际上调用的是Sync的innerRun()函数,我们继续查看Sync类型。 [java]  view plain copy print ?
  1. private volatile Thread runner;    

造函数,传递进来的就是最先说的那个mWorker   [java]  view plain copy print ?
  1. Sync(Callable callable) {    
  2.        this.callable = callable;    
  3.    }    
  4.     
  5.    ......               // 部分代码省略    
  6.    // innerRun函数    
  7.    void innerRun() {    
  8.        if (!compareAndSetState(READY, RUNNING))    
  9.            return;    
  10.     
  11.        runner = Thread.currentThread();    
  12.        if (getState() == RUNNING) { // recheck after setting thread    
  13.            V result;    
  14.            try {    
  15.                // 可以发现调用的是callable的.call()函数,即mWorker的call函数,而在mWorker的call函数中才真正的调用了doInBackground函数,至此线程真正启动了!    
  16.                result = callable.call();    
  17.            } catch (Throwable ex) {    
  18.                setException(ex);    
  19.                return;    
  20.            }    
  21.            set(result);    
  22.        } else {    
  23.            releaseShared(0); // cancel    
  24.        }    
  25.    }    

我们看到,最后调用了set(result);我们看看这段代码 :  [java]  view plain copy print ?
  1. protected void set(V v) {    
  2.      sync.innerSet(v);    
  3.  }    

我们在看看sync中的innerSet方法 :  [java]  view plain copy print ?
  1. void innerSet(V v) {    
  2.     for (;;) {    
  3.         int s = getState();    
  4.         if (s == RAN)    
  5.             return;    
  6.         if (s == CANCELLED) {    
  7.             // aggressively release to set runner to null,    
  8.             // in case we are racing with a cancel request    
  9.             // that will try to interrupt runner    
  10.             releaseShared(0);    
  11.             return;    
  12.         }    
  13.         if (compareAndSetState(s, RAN)) {    
  14.             result = v;    
  15.             releaseShared(0);    
  16.             done();"white-space:pre">       // 调用了done方法    
  17.             return;    
  18.         }    
  19.     }    
  20. }    

我们前面说过,在AsyncTask构造方法中创建的mFuture对象覆写了done方法,在这个方法中获取调用结果,最终通过postResult将结果投递给UI线程。
再来分析AsyncTask中的sHandler。这个sHandler实例实际上是AsyncTask内部类InternalHandler的实例,而InternalHandler正是继承了Handler,下面我们来分析一下它的代码: [java]  view plain copy print ?
  1. private static final int MESSAGE_POST_RESULT = 0x1//显示结果    
  2.    private static final int MESSAGE_POST_PROGRESS = 0x2;    //更新进度    
  3.    private static final int MESSAGE_POST_CANCEL = 0x3;  //取消任务    
  4.     
  5.    private static final InternalHandler sHandler = new InternalHandler();    
  6.     
  7. private static class InternalHandler extends Handler {    
  8.        @SuppressWarnings({"unchecked""RawUseOfParameterizedType"})    
  9.        @Override    
  10.        public void handleMessage(Message msg) {    
  11.            AsyncTaskResult result = (AsyncTaskResult) msg.obj;    
  12.            switch (msg.what) {    
  13.                case MESSAGE_POST_RESULT:    
  14.                    // There is only one result    
  15.                 //调用AsyncTask.finish方法    
  16.                    result.mTask.finish(result.mData[0]);    
  17.                    break;    
  18.                case MESSAGE_POST_PROGRESS:    
  19.                    //调用AsyncTask.onProgressUpdate方法    
  20.                 result.mTask.onProgressUpdate(result.mData);    
  21.                    break;    
  22.                case MESSAGE_POST_CANCEL:    
  23.                 //调用AsyncTask.onCancelled方法    
  24.                    result.mTask.onCancelled();    
  25.                    break;    
  26.            }    
  27.        }    
  28.    }    


我们看到,在处理消息时,遇到“MESSAGE_POST_RESULT”时,它会调用AsyncTask中的finish()方法,我们来看一下finish()方法的定义: [java]  view plain copy print ?
  1. private void finish(Result result) {    
  2.         if (isCancelled()) result = null;    
  3.         onPostExecute(result); //调用onPostExecute显示结果    
  4.         mStatus = Status.FINISHED;  //改变状态为FINISHED    
  5.     }    

原来finish()方法是负责调用onPostExecute(Result result)方法显示结果并改变任务状态的啊。 另外,在mFuture对象的done()方法里,构建一个消息时,这个消息包含了一个AsyncTaskResult类型的对象,然后在sHandler实例对象的handleMessage(Message msg)方法里,使用下面这种方式取得消息中附带的对象: [java]  view plain copy print ?
  1. AsyncTaskResult result = (AsyncTaskResult) msg.obj;    

这个AsyncTaskResult究竟是什么呢,它又包含什么内容呢?其实它也是AsyncTask的一个内部类,是用来包装执行结果的一个类,让我们来看一下它的代码结构:
[java]  view plain copy print ?
  1. @SuppressWarnings({"RawUseOfParameterizedType"})    
  2. private static class AsyncTaskResult {    
  3.     final AsyncTask mTask;    
  4.     final Data[] mData;    
  5.     
  6.     AsyncTaskResult(AsyncTask task, Data... data) {    
  7.         mTask = task;    
  8.         mData = data;    
  9.     }    
  10. }    

看以看到这个AsyncTaskResult封装了一个AsyncTask的实例和某种类型的数据集,我们再来看一下构建消息时的代码: [java]  view plain copy print ?
  1. //发送取消任务的消息    
  2. message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,    
  3.         new AsyncTaskResult(AsyncTask.this, (Result[]) null));    
  4. message.sendToTarget();    
  5. [java] view plaincopy  
  6. //发送显示结果的消息    
  7. message = sHandler.obtainMessage(MESSAGE_POST_RESULT,    
  8.          new AsyncTaskResult(AsyncTask.this, result));    
  9. message.sendToTarget();    

在处理消息时是如何使用这个对象呢,我们再来看一下: [java]  view plain copy print ?
  1. result.mTask.finish(result.mData[0]);    
  2.   
  3. result.mTask.onProgressUpdate(result.mData);    

概括来说,当我们调用execute(Params... params)方法后,execute方法会调用onPreExecute()方法,然后由ThreadPoolExecutor实例sExecutor执行一个FutureTask任务,这个过程中doInBackground(Params... params)将被调用,如果被开发者覆写的doInBackground(Params... params)方法中调用了publishProgress(Progress... values)方法,则通过InternalHandler实例sHandler发送一条MESSAGE_POST_PROGRESS消息,更新进度,sHandler处理消息时onProgressUpdate(Progress... values)方法将被调用;如果遇到异常,则发送一条MESSAGE_POST_CANCEL的消息,取消任务,sHandler处理消息时onCancelled()方法将被调用;如果执行成功,则发送一条MESSAGE_POST_RESULT的消息,显示结果,sHandler处理消息时onPostExecute(Result result)方法被调用。
下面看这个sDefaultExecutor
[java]  view plain copy
  1. private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;  
  2. public static final Executor SERIAL_EXECUTOR = new SerialExecutor();  
  3. private static class SerialExecutor implements Executor {  
  4.         final ArrayDeque mTasks = new ArrayDeque();  
  5.         Runnable mActive;  
  6.         public synchronized void execute(final Runnable r) {  
  7.             mTasks.offer(new Runnable() {  
  8.                 public void run() {  
  9.                     try {  
  10.                         r.run();  
  11.                     } finally {  
  12.                         scheduleNext();  
  13.                     }  
  14.                 }  
  15.             });  
  16.             if (mActive == null) {  
  17.                 scheduleNext();  
  18.             }  
  19.         }  
  20.         protected synchronized void scheduleNext() {  
  21.             if ((mActive = mTasks.poll()) != null) {  
  22.                 THREAD_POOL_EXECUTOR.execute(mActive);  
  23.             }  
  24.         }  
  25. }  
可以看到sDefaultExecutor其实为SerialExecutor的一个实例,其内部维持一个任务队列;直接看其execute(Runnable runnable)方法,将runnable放入mTasks队尾;
16-17行:判断当前mActive是否为空,为空则调用scheduleNext方法
20行:scheduleNext,则直接取出任务队列中的队首任务,如果不为null则传入THREAD_POOL_EXECUTOR进行执行。
下面看THREAD_POOL_EXECUTOR为何方神圣:
[java]  view plain copy
  1. public static final Executor THREAD_POOL_EXECUTOR  
  2.           =new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,  
  3.                     TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);  
可以看到就是一个自己设置参数的线程池,参数为:

[java]  view plain copy
  1. private static final int CORE_POOL_SIZE = 5;  
  2. private static final int MAXIMUM_POOL_SIZE = 128;  
  3. private static final int KEEP_ALIVE = 1;  
  4. private static final ThreadFactory sThreadFactory = new ThreadFactory() {  
  5. private final AtomicInteger mCount = new AtomicInteger(1);  
  6. public Thread newThread(Runnable r) {  
  7.      return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());  
  8.     }  
  9.  };  
  10. private static final BlockingQueue sPoolWorkQueue =  
  11.             new LinkedBlockingQueue(10);  

看到这里,大家可能会认为,背后原来有一个线程池,且最大支持128的线程并发,加上长度为10的阻塞队列,可能会觉得就是在快速调用138个以内的AsyncTask子类的execute方法不会出现问题,而大于138则会抛出异常。
其实不是这样的,我们再仔细看一下代码,回顾一下sDefaultExecutor,真正在execute()中调用的为sDefaultExecutor.execute:
[java]  view plain copy
  1. private static class SerialExecutor implements Executor {  
  2.         final ArrayDeque mTasks = new ArrayDeque();  
  3.         Runnable mActive;  
  4.         public synchronized void execute(final Runnable r) {  
  5.             mTasks.offer(new Runnable() {  
  6.                 public void run() {  
  7.                     try {  
  8.                         r.run();  
  9.                     } finally {  
  10.                         scheduleNext();  
  11.                     }  
  12.                 }  
  13.             });  
  14.             if (mActive == null) {  
  15.                 scheduleNext();  
  16.             }  
  17.         }  
  18.         protected synchronized void scheduleNext() {  
  19.             if ((mActive = mTasks.poll()) != null) {  
  20.                 THREAD_POOL_EXECUTOR.execute(mActive);  
  21.             }  
  22.         }  
  23. }  

可以看到,如果此时有10个任务同时调用execute(s synchronized)方法,第一个任务入队,然后在mActive = mTasks.poll()) != null被取出,并且赋值给mActivte,然后交给线程池去执行。然后第二个任务入队,但是此时mActive并不为null,并不会执行scheduleNext();所以如果第一个任务比较慢,10个任务都会进入队列等待;真正执行下一个任务的时机是,线程池执行完成第一个任务以后,调用Runnable中的finally代码块中的scheduleNext,所以虽然内部有一个线程池,其实调用的过程还是线性的。一个接着一个的执行,相当于单线程。

4、总结

到此源码解释完毕,由于代码跨度比较大,我们再回顾一下:

[java]  view plain copy
  1. public final AsyncTask execute(Params... params) {  
  2.         return executeOnExecutor(sDefaultExecutor, params);  
  3. }  
  4. public final AsyncTask executeOnExecutor(Executor exec,  
  5.             Params... params) {  
  6.         if (mStatus != Status.PENDING) {  
  7.             switch (mStatus) {  
  8.                 case RUNNING:  
  9.                     throw new IllegalStateException("Cannot execute task:"  
  10.                             + " the task is already running.");  
  11.                 case FINISHED:  
  12.                     throw new IllegalStateException("Cannot execute task:"  
  13.                             + " the task has already been executed "  
  14.                             + "(a task can be executed only once)");  
  15.             }  
  16.         }  
  17.   
  18.         mStatus = Status.RUNNING;  
  19.   
  20.         onPreExecute();  
  21.   
  22.         mWorker.mParams = params;  
  23.         exec.execute(mFuture);  
  24.   
  25.         return this;  
  26.     }  

18行:设置当前AsyncTask的状态为RUNNING,上面的switch也可以看出,每个异步任务在完成前只能执行一次。
20行:执行了onPreExecute(),当前依然在UI线程,所以我们可以在其中做一些准备工作。
22行:将我们传入的参数赋值给了mWorker.mParams ,mWorker为一个Callable的子类,且在内部的call()方法中,调用了doInBackground(mParams),然后得到的返回值作为postResult的参数进行执行;postResult中通过sHandler发送消息,最终sHandler的handleMessage中完成onPostExecute的调用。
23行:exec.execute(mFuture),mFuture为真正的执行任务的单元,将mWorker进行封装,然后由sDefaultExecutor交给线程池进行执行。


5、publishProgress

说了这么多,我们好像忘了一个方法:publishProgress

[java]  view plain copy
  1. protected final void publishProgress(Progress... values) {  
  2.         if (!isCancelled()) {  
  3.             sHandler.obtainMessage(MESSAGE_POST_PROGRESS,  
  4.                     new AsyncTaskResult(this, values)).sendToTarget();  
  5.         }  
  6. }  
也很简单,直接使用sHandler发送一个消息,并且携带我们传入的值;

[java]  view plain copy
  1. private static class InternalHandler extends Handler {  
  2.         @SuppressWarnings({"unchecked""RawUseOfParameterizedType"})  
  3.         @Override  
  4.         public void handleMessage(Message msg) {  
  5.             AsyncTaskResult result = (AsyncTaskResult) msg.obj;  
  6.             switch (msg.what) {  
  7.                 case MESSAGE_POST_RESULT:  
  8.                     // There is only one result  
  9.                     result.mTask.finish(result.mData[0]);  
  10.                     break;  
  11.                 case MESSAGE_POST_PROGRESS:  
  12.                     result.mTask.onProgressUpdate(result.mData);  
  13.                     break;  
  14.             }  
  15.         }  
  16. }  

在handleMessage中进行了我们的onProgressUpdate(result.mData);的调用。

6、AsyncTask曾经缺陷

记得以前有个面试题经常会问道:AsyncTask运行的原理是什么?有什么缺陷?

以前对于缺陷的答案可能是:AsyncTask在并发执行多个任务时发生异常。其实还是存在的,在3.0以前的系统中还是会以支持多线程并发的方式执行,支持并发数也是我们上面所计算的128,阻塞队列可以存放10个;也就是同时执行138个任务是没有问题的;而超过138会马上出现java.util.concurrent.RejectedExecutionException;

而在在3.0以上包括3.0的系统中会为单线程执行(即我们上面代码的分析);

空说无凭:下面看测试代码:

[java]  view plain copy
  1. package com.example.zhy_asynctask_demo01;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.ProgressDialog;  
  5. import android.os.AsyncTask;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8. import android.widget.TextView;  
  9.   
  10. public class MainActivity extends Activity  
  11. {  
  12.   
  13.     private static final String TAG = "MainActivity";  
  14.     private ProgressDialog mDialog;  
  15.     private TextView mTextView;  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState)  
  19.     {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.activity_main);  
  22.   
  23.         mTextView = (TextView) findViewById(R.id.id_tv);  
  24.   
  25.         mDialog = new ProgressDialog(this);  
  26.         mDialog.setMax(100);  
  27.         mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
  28.         mDialog.setCancelable(false);  
  29.           
  30.           
  31.         for(int i = 1 ;i <= 138 ; i++)  
  32.         {  
  33.             new MyAsyncTask2().execute();  
  34.         }  
  35.           
  36.         //new MyAsyncTask().execute();  
  37.   
  38.           
  39.     }  
  40.   
  41.     private class MyAsyncTask2 extends AsyncTask  
  42.     {  
  43.   
  44.         @Override  
  45.         protected Void doInBackground(Void... params)  
  46.         {  
  47.             try  
  48.             {  
  49.                 Log.e(TAG, Thread.currentThread().getName());  
  50.                 Thread.sleep(10000);  
  51.             } catch (InterruptedException e)  
  52.             {  
  53.                 e.printStackTrace();  
  54.             }  
  55.             return null;  
  56.         }  
  57.           
  58.     }  
  59. }  
可以看到我for循环中执行138个异步任务,每个异步任务的执行需要10s;下面使用2.2的模拟器进行测试:

输出结果为:

AsyncTask#1 - AsyncTask #128同时输出
然后10s后,另外10个任务输出。
可以分析结果,得到结论:AsyncTask在2.2的系统中同时支持128个任务并发,至少支持10个任务等待;

下面将138个任务,改成139个任务:

[java]  view plain copy
  1. for(int i = 1 ;i <= 139 ; i++)  
  2. {  
  3.     new MyAsyncTask2().execute();  
  4. }  
运行结果:会发生异常:java.util.concurrent.RejectedExecutionException ; 于是可以确定仅支持10个任务等待,超过10个则立即发生异常。
简单说一下出现异常的原因:现在是139个任务,几乎同时提交,线程池支持128个的并发,然后阻塞队列数量为10,此时当第11个任务提交的时候则会发生异常。

简单看一下源码:

[java]  view plain copy
  1. public static final Executor THREAD_POOL_EXECUTOR  
  2.            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);  
看ThreadPoolExecutor的execute方法:

[java]  view plain copy
  1. if (isRunning(c) && workQueue.offer(command)) {  
  2.             int recheck = ctl.get();  
  3.             if (! isRunning(recheck) && remove(command))  
  4.                 reject(command);  
  5.             else if (workerCountOf(recheck) == 0)  
  6.                 addWorker(nullfalse);  
  7.         }  
  8.         else if (!addWorker(command, false))  
  9.             reject(command);  

当阻塞队列满的时候workQueue.offer(command)返回false;然后执行addWorker(command,false)方法,如果返回false则执行reject()方法.

[java]  view plain copy
  1. private boolean addWorker(Runnable firstTask, boolean core) {  
  2. …  
  3. int wc = workerCountOf(c);  
  4.                 if (wc >= CAPACITY ||  
  5.                     wc >= (core ? corePoolSize : maximumPoolSize))  
  6.                     return false;  
  7. …  
  8. }  

可以看到当任务数目大于容量则返回false,最终在reject()中抛出异常。

上面就是使用2.2模拟器测试的结果;

下面将系统改为4.1.1,也就是我的测试机小米2s

把线程数改为139甚至1000,你可以看到任务一个接一个的在那缓慢的执行,不会抛什么异常,不过线程倒是1个1个的在那执行;


好了,如果现在大家去面试,被问到AsyncTask的缺陷,可以分为两个部分说,在3.0以前,最大支持128个线程的并发,10个任务的等待。在3.0以后,无论有多少任务,都会在其内部单线程执行;


更多相关文章

  1. 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
  2. 浅谈Android中的MVP与动态代理的结合
  3. Android(安卓)设计模式第三篇:模板方法模式
  4. Android(java)学习笔记95:Android原理揭秘系列之View、ViewGroup
  5. Flutter笔记---Flutter与Android之间的相互通信MethodChannel与E
  6. Android动态模糊效果的快速实现方法
  7. Android之单线程下载与多线程下载
  8. 一个方便集成的 Android(安卓)右滑返回上级 控件
  9. 【经验】android webview 后退键导致表单再次提交

随机推荐

  1. SqlServer中批量update语句
  2. SQL SERVER日志进行收缩的图文教程
  3. SQLyog连接MySQL8.0报2058错误的完美解决
  4. SQL Server怎么找出一个表包含的页信息(Pa
  5. sql server编写archive通用模板脚本实现
  6. Mysql8.0.17安装教程【推荐】
  7. C# ling to sql 取多条记录最大时间
  8. SQL Server查看login所授予的具体权限问
  9. SQL Server正确删除Windows认证用户的方
  10. SQL Server数据库中的表名称、字段比较