AsyncTask

来源:互联网 发布:java中怎么调用方法 编辑:程序博客网 时间:2024/06/16 21:16

首先从Android3.0开始,系统要求网络访问必须在子线程中进行,否则网络访问将会失败并抛出NetworkOnMainThreadException这个异常,这样做是为了避免主线程由于耗时操作所阻塞从而出现ANR现象。AsyncTask封装了线程池和Handler。AsyncTask有两个线程池:SerialExecutor和THREAD_POOL_EXECUTOR。前者是用于任务的排队,默认是串行的线程池:后者用于真正的执行任务,是并行的。系统默认会调用串行的线程池。AsyncTask还有一个Handler,叫InternalHandler,用于将执行环境从线程池切换到主线程。AsyncTask内部就是通过InternalHandler来发送任务执行的进度以及执行结束等消息。

AsyncTask排队执行过程:系统先把参数Params封装为FutureTask对象,它相当于Runnable,接着FutureTask交给SerialExcutor的execute方法,它先把FutureTask插入到任务队列tasks中,如果这个时候没有正在活动的AsyncTask任务,那么就会执行下一个AsyncTask任务,同时当一个AsyncTask任务执行完毕之后,AsyncTask会继续执行其他任务直到所有任务都被执行为止。


关于线程池,AsyncTask对应的线程池ThreadPoolExecutor都是进程范围内共享的,都是static的,所以是AsyncTask控制着进程范围内所有的子类实例。由于这个限制的存在,当使用默认线程池时,如果线程数超过线程池的最大容量,线程池就会爆掉(3.0默认串行执行,不会出现这个问题)。针对这种情况。可以尝试自定义线程池,配合AsyncTask使用。


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

AyncTask调用例子
[html] view plain copy
  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
  1. @MainThread  
  2. public final AsyncTask<Params, Progress, Result> execute(Params... params) {  
  3.     return executeOnExecutor(sDefaultExecutor, params);  
  4. }  

超简单,就一行。先看看executeOnExecutor函数:
[html] view plain copy
  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
  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
  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
  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
  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
  1. public class MyThreadPoolExecutor extends AbstractExecutorService  
然后调用AsyncTask的executeOnExecutor,把自己的MyThreadPoolExecutor对象传进去,达到自己想要的效果。
不过,还是推荐使用系统默认的,也就是排队执行的方式,除非有特殊需求,我们才搞特殊化处理。



原创粉丝点击