1.Android 3.0版本之前的AsyncTask
下面是Android 2.3.7版本的AsyncTask的部分源码。
1 public abstract class AsyncTask<Params, Progress, Result> { 2 private static final String LOG_TAG = "AsyncTask"; 3 private static final int CORE_POOL_SIZE = 5; 4 private static final int MAXIMUM_POOL_SIZE = 128; 5 private static final int KEEP_ALIVE = 1; 6 private static final BlockingQueue<Runnable> sWorkQueue = 7 new LinkedBlockingQueue<Runnable>(10); 8 private static final ThreadFactory sThreadFactory = new ThreadFactory() { 9 private final AtomicInteger mCount = new AtomicInteger(1); 10 public Thread newThread(Runnable r) { 11 return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); 12 } 13 }; 14 private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, 15 MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); 16 17 ... 18 }
在这里又看到了ThreadPoolExecutor,它的核心线程数是5个,线程池允许创建的最大线程数为128,非核心线程空闲等待新任务的最长时间为10秒。采用的阻塞队列是LinkedBlockingQueue,它的容量为10。3.0版本之前的AsyncTask有一个缺点就是,线程池最大的线程数为128,加上阻塞队列的10个任务,所以AsyncTask最多能同时容纳138个任务,当提交第139任务时就会执行饱和策略,默认抛出RejectedExecutionException异常。
2.Android 7.0版本的AsyncTask
在这里采用Android 7.0版本的AsyncTask作为例子,首先来看AsyncTask的构造函数:
1 public AsyncTask() { 2 mWorker = new WorkerRunnable<Params, Result>() {//1 3 public Result call() throws Exception { 4 mTaskInvoked.set(true); 5 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 6 Result result = doInBackground(mParams); 7 Binder.flushPendingCommands(); 8 return postResult(result); 9 } 10 }; 11 12 mFuture = new FutureTask<Result>(mWorker) {//2 13 @Override 14 protected void done() { 15 try { 16 postResultIfNotInvoked(get()); 17 } catch (InterruptedException e) { 18 android.util.Log.w(LOG_TAG, e); 19 } catch (ExecutionException e) { 20 throw new RuntimeException("An error occurred while executing doInBackground()", 21 e.getCause()); 22 } catch (CancellationException e) { 23 postResultIfNotInvoked(null); 24 } 25 } 26 }; 27 }
从注释1处看这个WorkerRunnable实现了Callable接口,并实现了它的call方法,在call方法中调用了doInBackground(mParams)来处理任务并得到结果,并最终调用postResult将结果投递出去。注释2处的FutureTask是一个可管理的异步任务,它实现了Runnable和Futrue这两个接口。因此它可以包装Runnable和Callable,并提供给Executor执行。也可以调用线程直接执行(FutureTask.run())。在这里WorkerRunnable作为参数传递给了FutureTask。这两个变量会暂时保存在内存中,稍后会用到它们。
当要执行AsyncTask时,需要调用它的execute方法,代码如下所示。
public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); }
execute方法又调用了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;//1 17 exec.execute(mFuture); 18 return this; 19 }
这里会首先调用 onPreExecute方法,在注释1处将AsyncTask的参数传给WorkerRunnable,从前面我们知道WorkerRunnable会作为参数传递给了FutureTask,因此,参数被封装到FutureTask中。接下来会调用exec的execute方法,并将mFuture也就是前面讲到的FutureTask传进去。这里exec是传进来的参数sDefaultExecutor,它是一个串行的线程池,它的代码如下所示。
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() {//1 6 public void run() { 7 try { 8 r.run();//2 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 }
从注释1处可以看出,当调用SerialExecutor 的execute方法时,会将FutureTask加入到mTasks中。当任务执行完或者当前没有活动的任务时都会执行scheduleNext方法,它会从mTasks取出FutureTask任务并交由THREAD_POOL_EXECUTOR处理。关于THREAD_POOL_EXECUTOR,后面会介绍。从这里看出SerialExecutor是串行执行的。在注释2处可以看到执行了FutureTask的run方法,它最终会调用WorkerRunnable的call方法。
前面我们提到call方法postResult方法将结果投递出去,postResult方法代码如下所示。
private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; }
在postResult方法中会创建Message,并将结果赋值给这个Message,通过getHandler方法得到Handler,并通过这个Handler发送消息,getHandler方法如下所示。
private static Handler getHandler() { synchronized (AsyncTask.class) { if (sHandler == null) { sHandler = new InternalHandler(); } return sHandler; } }
在getHandler方法中创建了InternalHandler,InternalHandler的定义如下所示。
1 private static class InternalHandler extends Handler { 2 public InternalHandler() { 3 super(Looper.getMainLooper()); 4 } 5 6 @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) 7 @Override 8 public void handleMessage(Message msg) { 9 AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj; 10 switch (msg.what) { 11 case MESSAGE_POST_RESULT: 12 // There is only one result 13 result.mTask.finish(result.mData[0]); 14 break; 15 case MESSAGE_POST_PROGRESS: 16 result.mTask.onProgressUpdate(result.mData); 17 break; 18 } 19 } 20 }
在接收到MESSAGE_POST_RESULT消息后会调用AsyncTask的finish方法:
1 private void finish(Result result) { 2 if (isCancelled()) { 3 onCancelled(result); 4 } else { 5 onPostExecute(result); 6 } 7 mStatus = Status.FINISHED; 8 }
如果AsyncTask任务被取消了则执行onCancelled方法,否则就调用onPostExecute方法。而正是通过onPostExecute方法我们才能够得到异步任务执行后的结果。
接着回头来看SerialExecutor ,线程池SerialExecutor主要用来处理排队,将任务串行处理。 SerialExecutor中调用scheduleNext方法时,将任务交给THREAD_POOL_EXECUTOR。THREAD_POOL_EXECUTOR同样是一个线程池,用来执行任务。
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4)); private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; private static final int KEEP_ALIVE_SECONDS = 30; private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128); public static final Executor THREAD_POOL_EXECUTOR; static { ThreadPoolExecutor threadPoolExecutor = new threadPoolExecutor ( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); threadPoolExecutor.allowCoreThreadTimeOut(true); THREAD_POOL_EXECUTOR = threadPoolExecutor; }
THREAD_POOL_EXECUTOR指的就是threadPoolExecutor,他的核心线程和线程池允许创建的最大线程数都是由CPU的核数来计算出来的。它采用的阻塞队列仍旧是LinkedBlockingQueue,容量为128。
到此, Android 7.0版本的AsyncTask的源码就分析完了,在AsyncTask中用到了线程池,线程池中运行线程并且又用到了阻塞队列,因此,本章前面介绍的知识在这一节中做了很好的铺垫。Android 3.0及以上版本用SerialExecutor作为默认的线程,它将任务串行的处理保证一个时间段只有一个任务执行,而3.0之前版本是并行处理的。关于3.0之前版本的缺点在3.0之后版本也不会出现,因为线程是一个接一个执行的,不会出现超过任务数而执行饱和策略。如果想要在3.0及以上版本使用并行的线程处理可以使用如下的代码:
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");
其中asyncTask是我们自定义的AsyncTask,当然也可以传入Java提供的线程池,比如传入CachedThreadPool。
asyncTask.executeOnExecutor(Executors.newCachedThreadPool(),"");
也可以传入自定义的线程池:
Executor exec =new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); asyncTask.executeOnExecutor(exec,"");