AsyncTask 相信大家对他的使用并不陌生,它是谷歌官方提供的一种轻量级别的异步任务类,底层封装的是两个线程池和一个Handler.sDefaultExecutor=SERIAL_EXECUTOR 用来Runnable排队用的, THREAD_POOL_EXECUTOR 是用来真正执行任务的.
我们先从 execute()开始分析,executeOnExecutor(Executor exec, Params... params) 真正执行的代码如下:
1 if (mStatus != Status.PENDING) { 2 switch (mStatus) { 3 case RUNNING: 4 throw new IllegalStateException("Cannot execute task:" 5 + " the task is already running."); 6 case FINISHED: 7 throw new IllegalStateException("Cannot execute task:" 8 + " the task has already been executed " 9 + "(a task can be executed only once)"); 10 } 11 } 12 13 mStatus = Status.RUNNING; 14 15 onPreExecute(); 16 17 mWorker.mParams = params; 18 exec.execute(mFuture); 19 20 return this; 21}
如果执行状态是Running(正在执行)或Finish(已经执行完了),抛出异常,所以一个AsyncTask 只能执行一次. 接着调用onPreExcute(),这就是为什么onPreEcxute是在执行实际的后台操作前被UI thread调用. 任务的真正执行是在exec.execute(mFuture) 中, exec 是 SerialExecutor 的一个对象,我们就去看看SerialExecutor 是如何工作的,代码如下:
1private 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}
我们可以知道AsyncTask在构造方法中把Params 参数转化为一个FutureTask,接着SerialExecutor 会把FutureTask对象插入到ArrayDeque 任务队列,ArrayDeque 内部使用数组存储数据,大小自增长的队列.从这里可以看书AsyncTask 是串行执行的,最终交给scheduleNext()去执行.
1public AsyncTask() { 2 mWorker = new WorkerRunnable<Params, Result>() { 3 public Result call() throws Exception { 4 mTaskInvoked.set(true); 5 6 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 7 //noinspection unchecked 8 Result result = doInBackground(mParams); 9 Binder.flushPendingCommands(); 10 return postResult(result); 11 } 12 }; 13 14 mFuture = new FutureTask<Result>(mWorker) { 15 [@Override](https://my.oschina.net/u/1162528) 16 protected void done() { 17 try { 18 postResultIfNotInvoked(get()); 19 } catch (InterruptedException e) { 20 android.util.Log.w(LOG_TAG, e); 21 } catch (ExecutionException e) { 22 throw new RuntimeException("An error occurred while executing doInBackground()", 23 e.getCause()); 24 } catch (CancellationException e) { 25 postResultIfNotInvoked(null); 26 } 27 } 28 }; 29}
我们在public AsyncTask() {}构造方法中可以得知mWorker 首先将mTaskInvoked.set(true) 接着调用doInBackground(mParams) 返回Result,最后将其返回值传递给postResult(result).
1private 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}
postResult ()获取一个InternalHandler ,通过InternalHandler 发送MESSAGE_POST_RESULT的消息,最终由InternalHandler 来处理消息
1 private static class InternalHandler extends Handler { 2 public InternalHandler() { 3 super(Looper.getMainLooper()); 4 } 5 6 @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) 7 [@Override](https://my.oschina.net/u/1162528) 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}
为了能让执行环境切换到主线程,这就要求InternalHandler 必须在主线中,所以AsyncTask必须在主线程中创建.
以上就是AsyncTask的工作原理分析. 通过以上分析我们可以得知:
-
- Task的实例必须在UI thread中创建
-
execute方法必须在UI thread中调用
-
不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法
-
该task只能被执行一次,否则多次调用时将会出现异常。 如果在子线程中创建调用 onPreExecute()也在创建AsyncTask的子线程中执行,doInBackground(Params...)在子线程中执行,onPostExecute(Result)和onProgressUpdate(Progress...)在主线程中
由于本人第一次写源码分析的文章,再加上本人表达能力有限,如若哪里有误,,还望多多拍砖,请与指正,谢谢