多个AsyncTask执行顺序:并行or串行

AsyncTask作为一个优秀的封装,很多人都在用,可是我估计很多人并不清楚多个AsyncTask对象到底是串行执行的,还是并行执行的,如果是并行的,那么最多同时执行几个异步任务呢?
源码面前无秘密,我们看一下源代码就知道了。
这里以Android-23为例。

AyncTask调用例子
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. AsyncTask task = new AsyncTask() {  
  2.      @Override  
  3.      protected Object doInBackground(Object[] params) {  
  4.          return null;  
  5.      }  
  6.  };  
  7.  task.execute();  
普通AsyncTask对象调用如上,主要是通过task.execute()来执行异步任务。那么execute到底做了什么呢?

AsyncTask的execute函数
看看实现:
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @MainThread  
  2. public final AsyncTask<Params, Progress, Result> execute(Params... params) {  
  3.     return executeOnExecutor(sDefaultExecutor, params);  
  4. }  

超简单,就一行。先看看executeOnExecutor函数:
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @MainThread  
  2.  public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,  
  3.          Params... params) {  
  4.      if (mStatus != Status.PENDING) {  
  5.          switch (mStatus) {  
  6.              case RUNNING:  
  7.                  throw new IllegalStateException("Cannot execute task:"  
  8.                          + " the task is already running.");  
  9.              case FINISHED:  
  10.                  throw new IllegalStateException("Cannot execute task:"  
  11.                          + " the task has already been executed "  
  12.                          + "(a task can be executed only once)");  
  13.          }  
  14.      }  
  15.   
  16.      mStatus = Status.RUNNING;  
  17.   
  18.      onPreExecute();  
  19.   
  20.      mWorker.mParams = params;  
  21.      exec.execute(mFuture);  
  22.   
  23.      return this;  
  24.  }  
主要看exec.execute(mFuture)这一行。
exec是什么呢?从execute函数里面的实现就可以看到,exec是sDefaultExecutor,那么sDefaultExecutor是什么玩意呢?
从一下代码可以清楚的看到:
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public static final Executor SERIAL_EXECUTOR = new SerialExecutor();  
  2.   
  3. private static final int MESSAGE_POST_RESULT = 0x1;  
  4. private static final int MESSAGE_POST_PROGRESS = 0x2;  
  5.   
  6. private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;  

sDefaultExecutor是SerialExecutor的一个实例,而且它是个静态变量。也就是说,一个进程里面所有AsyncTask对象都共享同一个SerialExecutor对象。
那么所有的秘密就在于SerialExecutor的execute函数了。

SerialExecutor的execute函数
直接贴出SerialExecutor的实现:
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. private static class SerialExecutor implements Executor {  
  2.     final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();  
  3.     Runnable mActive;  
  4.   
  5.     public synchronized void execute(final Runnable r) {  
  6.         mTasks.offer(new Runnable() {  
  7.             public void run() {  
  8.                 try {  
  9.                     r.run();  
  10.                 } finally {  
  11.                     scheduleNext();  
  12.                 }  
  13.             }  
  14.         });  
  15.         if (mActive == null) {  
  16.             scheduleNext();  
  17.         }  
  18.     }  
  19.   
  20.     protected synchronized void scheduleNext() {  
  21.         if ((mActive = mTasks.poll()) != null) {  
  22.             THREAD_POOL_EXECUTOR.execute(mActive);  
  23.         }  
  24.     }  
  25. }  

代码本身很简单,从execute里面就能看出,异步任务r被放到了ArrayDeque对象mTasks中,然后通过scheduleNext()来从mTasks里面得到一个任务去一个后台线程执行。
在一个异步任务执行后,再次调用scheduleNext来执行下一个任务(run函数)。
所以,很清楚,其实SerialExecutor是一个一个执行任务的,而所有的AsyncTask对象又共享同一个SerialExecutor对象(静态成员)。
所以,我们可以肯定: 至少在Android-23 SDK里面,多个AsyncTask对象是串行执行的。
实际是不是呢,做个实验就知道:

测试代码超简单,就是创建3个AsyncTask对象,做了一样的事情,就是在doInBackground里面打印log。
我们从log可以清楚的看到,AsyncTask对象1,2,3是串行执行的。
这也证实了,Android-23 sdk里面 多个AsyncTask对象确实是串行执行的。

如何并行执行多个AsyncTask对象
那么有没有办法并行执行呢?肯定有了。
看AsyncTask的实现,里面有个Executor
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public static final Executor THREAD_POOL_EXECUTOR  
  2.          = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,  
  3.                  TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);  
如果我们直接使用THREAD_POOL_EXECUTOR会怎么样呢?
看下图:

这次的执行顺序跟上次不一样了。可以看出好像3个任务并行执行了。不像之前的排队执行。
关于THREAD_POOL_EXECUTOR,有兴趣可以看进去,大致的意思就是,
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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;  
这是个线程池,有两个概念,一个是线程池里面核心线程数,一个是最大线程数。从上面的定义可以大概看出来,核心线程数是CPU个数+1,最大是CPU个数 * 2 + 1.
至于怎么调度执行,那就有一套算法了,这里就不介绍了。但是有一点可以肯定,它不是排队在一个线程里面执行的,所以也就看到了上面的结果。

实际上,我们也可以自己实现 一个执行器,如:
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class MyThreadPoolExecutor extends AbstractExecutorService  
然后调用AsyncTask的executeOnExecutor,把自己的MyThreadPoolExecutor对象传进去,达到自己想要的效果。
不过,还是推荐使用系统默认的,也就是排队执行的方式,除非有特殊需求,我们才搞特殊化处理。


原文链接:http://blog.csdn.net/zj510/article/details/51622597
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值