Loading

Android AsyncTask 源码解析

1. 官方介绍

public abstract class AsyncTask 
extends Object 

java.lang.Object
   ↳ android.os.AsyncTask<Params, Progress, Result>

 

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as ExecutorThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate andonPostExecute.

翻译

  • AsyncTask使适当的和容易使用的UI线程。这类允许执行后台操作和发布的结果在UI线程上无需操纵线程和/或处理程序。AsyncTask被设计成一个助手类线程和处理程序和不构成通用线程框架。理想情况下应使用asynctask简称操作(最多几秒钟)。如果你需要保持线程运行很长一段时间,强烈建议你使用各种java.util提供的api。并发包如遗嘱执行人,ThreadPoolExecutor FutureTask。异步任务被定义为一个计算,运行在一个后台线程,其结果发表在UI线程上。异步任务被定义为3泛型类型,称为Params,进展和结果,和4个步骤,称为onPreExecute,doInBackground,onProgressUpdate,onPostExecute。
  • 简单来说AsyncTasck是用来处理耗时的操作(如:网络请求/下载图片等等...),说白了就是相当于对Thread+Handler的一种封装,封装了ThreadPool, 比直接使用Thread效率要高,使用它更编码更简洁,更高效.

 

2.使用方法

  •  举一个列子给大家看看
    •  
      package com.edwin.demoasynctask;
      
      import android.app.ProgressDialog;
      import android.os.AsyncTask;
      import android.os.Bundle;
      import android.support.v7.app.AppCompatActivity;
      import android.util.Log;
      import android.widget.Toast;
      
      public class MainActivity extends AppCompatActivity {
          private String TAG = "Edwin";
          private ProgressDialog mProgressDialog;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              new MyAsyncTask().execute("网址地址", "请求参数");
          }
      
          /**
           * AsyncTask<Params, Progress, Result>三个参数分别介绍一下
           * Params 启动任务执行的输入参数,比如HTTP请求的URL。
           * Progress 后台任务执行的百分比,比如下载的进度值。
           * Result 后台执行任务最终返回的结果,比如String。
           * <p/>
           * GO
           * 这里我做一个模拟下载文件的操作
           */
          private class MyAsyncTask extends AsyncTask<String, Integer, String> {
              /**
               * 1.在分线程工作开始之前在UI线程中执行,初始化进度条视图
               */
              @Override
              protected void onPreExecute() {
                  //TODO 准备初始化View
                  mProgressDialog = new ProgressDialog(MainActivity.this);
                  mProgressDialog.setMax(100);
                  mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                  mProgressDialog.setCancelable(false);
                  mProgressDialog.show();
                  Log.e(TAG, "onPreExecute");
              }
      
              /**
               * 2.在分线程中执行,完成任务的主要工作,通常需要较长的时间
               *
               * @param params url请求参数等等..
               * @return 请求之后得到的结果
               */
              @Override
              protected String doInBackground(String... params) {
                  //TODO 做一些耗时的操作
                  String url = params[0];//获取url参数进行网络请求操作
      
                  Log.e(TAG, "doInBackground");
                  int i = 0;
                  // 下面我们模拟数据的加载,耗时的任务
                  for (i = 0; i < 100; i++) {
                      try {
                          Thread.sleep(100);
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                      //在分线程中, 发布当前进度
                      publishProgress(i);
                  }
                  //返回结果
                  return "结果:" + i;
              }
      
              /**
               * 3.在主线程中更新进度
               *
               * @param values 进度值
               */
              @Override
              protected void onProgressUpdate(Integer... values) {
                  //TODO 获取进度值,更新View
                  mProgressDialog.setProgress(values[0]);
                  Log.e(TAG, "onProgressUpdate values[0] = " + values[0]);
      
              }
      
              /**
               * 4.执行完之后的结果
               *
               * @param result 结果
               */
              @Override
              protected void onPostExecute(String result) {
                  //TODO 获取结果,关闭View
                  mProgressDialog.dismiss();
                  Log.e(TAG, "onPostExecute result = " + result);
                  Toast.makeText(MainActivity.this, "文件下载成功", Toast.LENGTH_SHORT).show();
              }
          }
      }

       

  • 效果图
    •  
    •  

 

3. 源码解析

  •  AsyncTask初始化操作分析

    •  1 /**
       2      * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
       3      */
       4     public AsyncTask() {
       5         mWorker = new WorkerRunnable<Params, Result>() {
       6             public Result call() throws Exception {
       7                 mTaskInvoked.set(true);
       8 
       9                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      10                 //noinspection unchecked
      11                 Result result = doInBackground(mParams);
      12                 Binder.flushPendingCommands();
      13                 return postResult(result);
      14             }
      15         };
      16 
      17         mFuture = new FutureTask<Result>(mWorker) {
      18             @Override
      19             protected void done() {
      20                 try {
      21                     postResultIfNotInvoked(get());
      22                 } catch (InterruptedException e) {
      23                     android.util.Log.w(LOG_TAG, e);
      24                 } catch (ExecutionException e) {
      25                     throw new RuntimeException("An error occurred while executing doInBackground()",
      26                             e.getCause());
      27                 } catch (CancellationException e) {
      28                     postResultIfNotInvoked(null);
      29                 }
      30             }
      31         };
      32     }
      • 第5行是初始化的一些参数,用于存放我们传入的参数execute(Params... params),源码点进去看WorkerRunnable是一个抽象类实现了Callable

        •   
           1 private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
           2         Params[] mParams;
           3     }
           4 
           5     @SuppressWarnings({"RawUseOfParameterizedType"})
           6     private static class AsyncTaskResult<Data> {
           7         final AsyncTask mTask;
           8         final Data[] mData;
           9 
          10         AsyncTaskResult(AsyncTask task, Data... data) {
          11             mTask = task;
          12             mData = data;
          13         }
          14     }

           

      • 第17行是初始化FutureTask而穿进去的参数又是mWorker重写done方法,在完成的时候调用onCancelled()或者onPostExecute()。看源码追踪
        • 1  通过源码postResultfNotInvoked(get()),postResultfNotInvoked(null);点进入如下
          2  private void postResultIfNotInvoked(Result result) {
          3         final boolean wasTaskInvoked = mTaskInvoked.get(); //如果不为true就执行,因在初始化的时候已经设为了true,所以不会执行
          4         if (!wasTaskInvoked) {
          5             postResult(result);
          6         }
          7     }

 

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

       

      • 先看第7行一个switch语句先判断当前的状态,Status是一个枚举类型共三种情况(等待PENDING/运行RUNNING/完成FINISHED),
      • 哈哈,看执行到21行代码,很熟悉了吧onPreExecute()初始化的操作,在UI线程做一些准备工作啦!
      • 接走执行到23行,刚才我们一进来就讲啦mWorker初始化操作了,他是一个抽象类,这时候我们把我们传入进来的参数赋值给它。
      • 最好第24行执行一个异步操作。mFuture参数在初始化的地方讲到了,下面我们之间深入看源码。
    • 好,我们在此回过去看FutureTask初始化后done方法里的方法postResultIfNotInvoked(get())和postResultIfNotInvoked(null)
      •   
         1 private void postResultIfNotInvoked(Result result) {
         2         final boolean wasTaskInvoked = mTaskInvoked.get();
         3         if (!wasTaskInvoked) {
         4             postResult(result);  //慢慢深入
         5         }
         6     }
         7 
         8 
         9 private Result postResult(Result result) {
        10         @SuppressWarnings("unchecked")
        11         Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
        12                 new AsyncTaskResult<Result>(this, result));
        13         message.sendToTarget();
        14         return result;
        15     }

         

        • 第11行代码,哇靠!通过Handler发送消息给UI线程,那就去看看Handler的初始化操作
          •   
             1 private static Handler getHandler() {
             2         synchronized (AsyncTask.class) {
             3             if (sHandler == null) {
             4                 sHandler = new InternalHandler();
             5             }
             6             return sHandler;
             7         }
             8     }
             9 
            10 
            11 private static class InternalHandler extends Handler {
            12         public InternalHandler() {
            13             super(Looper.getMainLooper());
            14         }
            15 
            16         @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
            17         @Override
            18         public void handleMessage(Message msg) {
            19             AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
            20             switch (msg.what) {
            21                 case MESSAGE_POST_RESULT:
            22                     // There is only one result
            23                     result.mTask.finish(result.mData[0]);//源码跟踪进入调用的是onPostExecute()
            24                     break;
            25                 case MESSAGE_POST_PROGRESS:
            26                     result.mTask.onProgressUpdate(result.mData); //调用onProgressUpdate熟悉吧。
            27                     break;
            28             }
            29         }
            30     }

             

    • 我们在回过头来看看,调用execute方法,最终调用的是executeOnExecutor方法,他里面有一个设置好的参数sDefaultExecutor,好对他下手拨开皮看看
      •   逆向分析—颜色一一对应
         1  public final AsyncTask<Params, Progress, Result> execute(Params... params) {
         2         return executeOnExecutor(sDefaultExecutor, params);
         3     }
         4 
         5 private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
         6 
         7 public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
         8 
         9 private static class SerialExecutor implements Executor {
        10         final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        11         Runnable mActive;
        12 
        13         public synchronized void execute(final Runnable r) {
        14             mTasks.offer(new Runnable() {
        15                 public void run() {
        16                     try {
        17                         r.run();
        18                     } finally {
        19                         scheduleNext();
        20                     }
        21                 }
        22             });
        23             if (mActive == null) {
        24                 scheduleNext();
        25             }
        26         }
        27 
        28         protected synchronized void scheduleNext() {
        29             if ((mActive = mTasks.poll()) != null) {
        30                 THREAD_POOL_EXECUTOR.execute(mActive);
        31             }
        32         }
        33     }
        34 
        35 
        36 public static final Executor THREAD_POOL_EXECUTOR
        37             = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
        38                     TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
        39 
        40 
        41 
        42   private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();//可用的CPU个数
        43   private static final int CORE_POOL_SIZE = CPU_COUNT + 1;//线程池大小
        44   private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;//最大线程
        45   private static final int KEEP_ALIVE = 1;//维持时间

         

4. AsyncTask曾经缺陷

  • API11以前的源码 
    •   
       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 
       5 private static final BlockingQueue<Runnable> sWorkQueue =
       6     new LinkedBlockingQueue<Runnable>(10);
       7 
       8 private static final ThreadPoolExecutor sExecutor = 
       9     new ThreadPoolExecutor(CORE_POOL_SIZE,MAXIMUM_POOL_SIZE, KEEP_ALIVE, 
      10         TimeUnit.SECONDS, sWorkQueue, sThreadFactory);

       

  • API11以后的源码 
    •   
       1     private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
       2     private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
       3     private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
       4     private static final int KEEP_ALIVE = 1;
       5     private static final BlockingQueue<Runnable> sPoolWorkQueue =
       6             new LinkedBlockingQueue<Runnable>(128);
       7 
       8     /**
       9      * An {@link Executor} that can be used to execute tasks in parallel.
      10      * 一个可用于并行执行的任务。多线程模式
      11      */
      12     public static final Executor THREAD_POOL_EXECUTOR
      13             = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
      14                     TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
      15 
      16     /**
      17      * An {@link Executor} that executes tasks one at a time in serial
      18      * order.  This serialization is global to a particular process.
      19      * 一个串行执行,一次完成一项任务秩序。这个序列化是全球性的一个特定的过程。单线程模式
      20      */
      21     public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

       

  • 结论
    • 在3.0以前,最大支持128个线程的并发,10个任务的等待。
    • 在3.0以后,无论有多少任务,都会在其内部单线程执行;

       

 

 

posted @ 2016-06-19 22:53  浩友  阅读(339)  评论(0编辑  收藏  举报