【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

1 背景

Android异步处理机制一直都是Android的一个核心,也是应用工程师面试的一个知识点。前面我们分析了Handler异步机制原理(不了解的可以阅读我的《Android异步消息处理机制详解及源码分析》文章),这里继续分析Android的另一个异步机制AsyncTask的原理。

当使用线程和Handler组合实现异步处理时,当每次执行耗时操作都创建一条新线程进行处理,性能开销会比较大。为了提高性能我们使用AsyncTask实现异步处理(其实也是线程和handler组合实现),因为其内部使用了java提供的线程池技术,有效的降低了线程创建数量及限定了同时运行的线程数,还有一些针对性的对池的优化操作。所以说AsyncTask是Android为我们提供的方便编写异步任务的工具类。

【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

2 实例演示

先看下使用AsyncTask模拟下载的效果图:

看下代码,如下:

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. new TestAsyncTask(this).execute();
  7. }
  8. static final class TestAsyncTask extends AsyncTask<Void, Integer, Boolean> {
  9. //如上三个泛型参数从左到右含义依次为:
  10. //1. 在执行AsyncTask时需要传入的参数,可用于在后台任务中使用。
  11. //2. 后台任务执行时,如果需要在界面上显示当前的进度,则使用这个。
  12. //3. 当任务执行完毕后,如果需要对结果进行返回,则使用这个。
  13. private Context mContext = null;
  14. private ProgressDialog mDialog = null;
  15. private int mCount = 0;
  16. public TestAsyncTask(Context context) {
  17. mContext = context;
  18. }
  19. //在后台任务开始执行之间调用,用于进行一些界面上的初始化操作
  20. protected void onPreExecute() {
  21. super.onPreExecute();
  22. mDialog = new ProgressDialog(mContext);
  23. mDialog.setMax(100);
  24. mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  25. mDialog.show();
  26. }
  27. //这个方法中的所有代码都会在子线程中运行,我们应该在这里去处理所有的耗时任务
  28. protected Boolean doInBackground(Void... params) {
  29. while (mCount < 100) {
  30. publishProgress(mCount);
  31. mCount += 20;
  32. try {
  33. Thread.sleep(1000);
  34. } catch (InterruptedException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. return true;
  39. }
  40. //当在后台任务中调用了publishProgress(Progress...)方法后,这个方法就很快会被调用
  41. protected void onProgressUpdate(Integer... values) {
  42. super.onProgressUpdate(values);
  43. mDialog.setProgress(values[0]);
  44. }
  45. //当后台任务执行完毕并通过return语句进行返回时,这个方法就很快会被调用
  46. protected void onPostExecute(Boolean aBoolean) {
  47. super.onPostExecute(aBoolean);
  48. if (aBoolean && mDialog != null && mDialog.isShowing()) {
  49. mDialog.dismiss();
  50. }
  51. }
  52. }
  53. }

可以看见Android帮我们封装好的AsyncTask还是很方便使用的,咱们不做过多说明。接下来直接分析源码。

【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

3 Android5.1.1(API 22)AsyncTask源码分析

通过源码可以发现AsyncTask是一个抽象类,所以我们在在上面使用时需要实现它。

那怎么下手分析呢?很简单,我们就依据上面示例的流程来分析源码,具体如下。

3-1 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. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
  9. //noinspection unchecked
  10. return postResult(doInBackground(mParams));
  11. }
  12. };
  13. mFuture = new FutureTask<Result>(mWorker) {
  14. @Override
  15. protected void done() {
  16. try {
  17. postResultIfNotInvoked(get());
  18. } catch (InterruptedException e) {
  19. android.util.Log.w(LOG_TAG, e);
  20. } catch (ExecutionException e) {
  21. throw new RuntimeException("An error occured while executing doInBackground()",
  22. e.getCause());
  23. } catch (CancellationException e) {
  24. postResultIfNotInvoked(null);
  25. }
  26. }
  27. };
  28. }

看见注释没有,AsyncTask的实例化只能在UI线程中。然后整个构造函数就只初始化了两个AsyncTask类的成员变量(mWorker和mFuture)。mWorker

为匿名内部类的实例对象WorkerRunnable(实现了Callable接口),mFuture为匿名内部类的实例对象FutureTask,传入了mWorker作为形参(重写了

FutureTask类的done方法)。

3-2 AsyncTask的execute方法源码分析

正如上面实例一样,得到AsyncTask实例化对象之后就执行了execute方法,所以看下execute方法的源码,如下:

  1. public final AsyncTask<Params, Progress, Result> execute(Params... params) {
  2. return executeOnExecutor(sDefaultExecutor, params);
  3. }

可以看见,execute调运了executeOnExecutor方法,executeOnExecutor方法除过传入了params形参以外,还传入了一个static的SerialExecutor对象

(SerialExecutor实现了Executor接口)。继续看下executeOnExecutor源码,如下:

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

首先判断AsyncTask异步任务的状态,当处于RUNNING和FINISHED时就报IllegalStateException非法状态异常。由此可以看见一个AsyncTask的

execute方法只能被调运一次。接着看见17行onPreExecute();没有?看下这个方法源码,如下:

  1. /**
  2. * Runs on the UI thread before {@link #doInBackground}.
  3. *
  4. * @see #onPostExecute
  5. * @see #doInBackground
  6. */
  7. protected void onPreExecute() {
  8. }

空方法,而且通过注释也能看见,这不就是我们AsyncTask中第一个执行的方法吗?是的。

回过头继续往下看,看见20行exec.execute(mFuture);代码没?exec就是形参出入的上面定义的static SerialExecutor对象(SerialExecutor实现了Executor接口),所以execute就是SerialExecutor静态内部类的方法喽,在执行execute方法时还传入了AsyncTask构造函数中实例化的第二个成员变量mFuture。我们来看下SerialExecutor静态内部类的代码,如下:

  1. private static class SerialExecutor implements Executor {
  2. final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
  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. }

在源码中可以看见,SerialExecutor在AsyncTask中是以常量的形式被使用的,所以在整个应用程序中的所有AsyncTask实例都会共用同一个

SerialExecutor对象。接着可以看见,SerialExecutor是使用ArrayDeque这个队列来管理Runnable对象的,如果我们一次性启动了很多个任务,首先在第一次运行execute()方法的时候会调用ArrayDeque的offer()方法将传入的Runnable对象添加到队列的最后,然后判断mActive对象是不是等于null,第一次运行是null,然后调用scheduleNext()方法,在这个方法中会从队列的头部取值,并赋值给mActive对象,然后调用THREAD_POOL_EXECUTOR去执行取出的取出的Runnable对象。之后如果再有新的任务被执行时就等待上一个任务执行完毕后才会得到执行,所以说同一时刻只会有一个线程正在执行,其余的均处于等待状态,这就是SerialExecutor类的核心作用。

我们再来看看上面用到的THREAD_POOL_EXECUTOR与execute,如下:

  1. public abstract class AsyncTask<Params, Progress, Result> {
  2. ......
  3. private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
  4. private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
  5. private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
  6. private static final int KEEP_ALIVE = 1;
  7. private static final ThreadFactory sThreadFactory = new ThreadFactory() {
  8. private final AtomicInteger mCount = new AtomicInteger(1);
  9. public Thread newThread(Runnable r) {
  10. return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
  11. }
  12. };
  13. private static final BlockingQueue<Runnable> sPoolWorkQueue =
  14. new LinkedBlockingQueue<Runnable>(128);
  15. /**
  16. * An {@link Executor} that can be used to execute tasks in parallel.
  17. */
  18. public static final Executor THREAD_POOL_EXECUTOR
  19. = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
  20. TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
  21. ......
  22. }

看见没有,实质就是在一个线程池中执行,这个THREAD_POOL_EXECUTOR线程池是一个常量,也就是说整个App中不论有多少AsyncTask都只有这

一个线程池。也就是说上面SerialExecutor类中execute()方法的所有逻辑就是在子线程中执行,注意SerialExecutor的execute方法有一个Runnable参数

,这个参数就是mFuture对象,所以我们看下FutureTask类的run()方法,如下源码:

  1. public void run() {
  2. if (state != NEW ||
  3. !UNSAFE.compareAndSwapObject(this, runnerOffset,
  4. null, Thread.currentThread()))
  5. return;
  6. try {
  7. Callable<V> c = callable;
  8. if (c != null && state == NEW) {
  9. V result;
  10. boolean ran;
  11. try {
  12. result = c.call();
  13. ran = true;
  14. } catch (Throwable ex) {
  15. result = null;
  16. ran = false;
  17. setException(ex);
  18. }
  19. if (ran)
  20. set(result);
  21. }
  22. } finally {
  23. // runner must be non-null until state is settled to
  24. // prevent concurrent calls to run()
  25. runner = null;
  26. // state must be re-read after nulling runner to prevent
  27. // leaked interrupts
  28. int s = state;
  29. if (s >= INTERRUPTING)
  30. handlePossibleCancellationInterrupt(s);
  31. }
  32. }

看见没有?第7行的c = callable;其实就是AsyncTask构造函数中实例化FutureTask对象时传入的参数mWorker。12行看见result = c.call();没有?

其实就是调运WorkerRunnable类的call方法,所以我们回到AsyncTask构造函数的WorkerRunnable匿名内部内中可以看见如下:

  1. mWorker = new WorkerRunnable<Params, Result>() {
  2. public Result call() throws Exception {
  3. mTaskInvoked.set(true);
  4. Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
  5. //noinspection unchecked
  6. return postResult(doInBackground(mParams));
  7. }
  8. };

看见没有?在postResult()方法的参数里面,我们可以看见doInBackground()方法。所以这验证了我们上面例子中使用的AsyncTask,首先在主线程执

行onPreExecute方法,接着在子线程执行doInBackground方法,所以这也就是为什么我们可以在doInBackground()方法中去处理耗时操作的原因了

,接着等待doInBackground方法耗时操作执行完毕以后将返回值传递给了postResult()方法。所以我们来看下postResult这个方法的源码,如下:

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

先看下这个getHandler拿到的是哪个Handler吧,如下:

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

看见没有,拿到的是MainLooper,也就是说在在UI线程中的Handler(不清楚的请阅读《Android异步消息处理机制详解及源码分析》文章)。所以

上面的方法其实就是将子线程的数据发送到了UI来处理,也就是通过MESSAGE_POST_RESULT在handleMessage来处理。所以我们继续看

handleMessage中的result.mTask.finish(result.mData[0]);就会发现finish的代码如下:

  1. private void finish(Result result) {
  2. if (isCancelled()) {
  3. onCancelled(result);
  4. } else {
  5. onPostExecute(result);
  6. }
  7. mStatus = Status.FINISHED;
  8. }

看见没有?依据返回值true与false回调AsyncTask的onPostExecute或者onCancelled方法。

到此是不是会好奇onProgressUpdate方法啥时候调运的呢?继续往下看可以发现handleMessage方法中的MESSAGE_POST_PROGRESS不就是回调我们UI Thread中的onProgressUpdate方法吗?那怎么样才能让他回调呢?追踪MESSAGE_POST_PROGRESS消息你会发现如下:

  1. protected final void publishProgress(Progress... values) {
  2. if (!isCancelled()) {
  3. getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
  4. new AsyncTaskResult<Progress>(this, values)).sendToTarget();
  5. }
  6. }

额,没意思了。这不就是我们上面例子中的在子线程的doInBackground耗时操作中调运通知回调onProgressUpdate的方法么。

看见没有,AsyncTask的实质就是Handler异步消息处理机制(不清楚的请阅读《Android异步消息处理机制详解及源码分析》文章),只是对线程做了优化处理和封装而已。

【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

4 为当年低版本AsyncTask的臭名正身

接触Android比较久的可能都知道,在Android 3.0之前是并没有SerialExecutor这个类的(上面有分析)。那些版本的代码是直接创建了指定大小的线程池常量来执行task的。其中MAXIMUM_POOL_SIZE = 128;,所以那时候如果我们应用中一个界面需要同时创建的AsyncTask线程大于128(批量获取数据,譬如照片浏览瀑布流一次加载)程序直接就挂了。所以当时的AsyncTask因为这个原因臭名昭著。

回过头来看看现在高版本的AsyncTask,是不是没有这个问题了吧?因为现在是顺序执行的。而且更劲爆的是现在的AsyncTask还直接提供了客户化实现Executor接口功能,使用如下方法执行AsyncTask即可使用自定义Executor,如下:

  1. public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
  2. Params... params) {
  3. ......
  4. return this;
  5. }

可以看出,在3.0以上版中AsyncTask已经不存在那个臭名昭著的Bug了,所以可以放心使用了,妈妈再也不用担心我的AsyncTask出Bug了。

【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

5 AsyncTask与Handler异步机制对比

前面文章也分析过Handler了,这里也分析了AsyncTask,现在把他们两拽一起来比较比较。具体如下:

  • AsyncTask是对Handler与Thread的封装。

  • AsyncTask在代码上比Handler要轻量级别,但实际上比Handler更耗资源,因为AsyncTask底层是一个线程池,而Handler仅仅就是发送了一个消息队列。但是,如果异步任务的数据特别庞大,AsyncTask线程池比Handler节省开销,因为Handler需要不停的new Thread执行。

  • AsyncTask的实例化只能在主线程,Handler可以随意,只和Looper有关系。

6 AsyncTask总结

到此整个Android的AsyncTask已经分析完毕,相信你现在对于AsyncTask会有一个很深入的理解与认识了。

【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

版权声明:本文为博主原创文章,未经博主允许不得转载。