开始分析
从最常调用的 execute(Params... params) 方法开始
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
先回调onPreExecute(),将任务params封装进mWorker,再以mFuture作为参数,调用exec的execute()方法。
ok..mWorker是啥,mFuture是什么,参数sDefaultExecutor又是什么?
别着急,一个一个地看
mWorker
private final WorkerRunnable<Params, Result> mWorker;
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
//...
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
WorkerRunnable类型的mWorker封装了Params,并且实现了Callable接口。在call()方法中回调doInBackground()方法,并将结果作为参数调用postResult()方法。
postResult()其实是通过handle调用finish()方法,而finish()方法则回调我们实现的onCancelled()或onPostExecute()方法。
mFuture
private final FutureTask<Result> mFuture;
public AsyncTask() {
//...
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
public class FutureTask<V> implements RunnableFuture<V> {
//...
public void run() {
//...
V result;
result = c.call();
//...
}
}
//...
}
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
很简单,mFuture其实是一个Runable对象,它的run()方法调用mWorker的call()方法。
SERIAL_EXECUTOR、sDefaultExecutor和THREAD_POOL_EXECUTOR
public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
它们都是静态的。
THREAD_POOL_EXECUTOR是一个线程池对象,用于处理AsyncTask的异步任务
sDefaultExecutor是一个Executor对象,内部管理一个名为mTasks的队列,这个对象有两个方法,分别是scheduleNext()和实现接口的execute(Runnable r)方法。
-
scheduleNext()方法是从mTasks队头取出一个Runnable任务赋值给mActive,并交由THREAD_POOL_EXECUTOR线程池处理。
-
execute(Runnable r)作了以下几件事:
- 把传入Runnable型的参数进一步封装,执行完任务后调用scheduleNext()
- 将封装后的Runnable对象放入mTasks队尾
- 如果当前mActive为空,则调用scheduleNext()
几个问题
考虑首次调用sDefaultExecutor的execute()方法会出现什么情况?
一个任务还没执行完,再次调用sDefaultExecutor的execute()方法呢?
执行完队列的任务后,再次调用execute()方法呢?
至此,AsyncTask的基本实现原理已经了解,也弄清了几个常见方法是何时被回调的了,那么对AsyncTask的源码分析就可以告一段落了。
分析要点
- 带着问题。常用回调是何时进行的,例如onPreExecute()、doInBackground()、onPostExecute()等。
- 不要过多纠结细节。比如FutureTask这个类这么多方法都有什么用,我们的目的是分析AsyncTask实现原理,只要关心它是Runable类型的,以及它在run()方法中调用mWorker的call()方法就行了。
- 注意分析顺序,比如从我们调用的execute(Params... params)方法开始,查看它的实现。
- 弄清楚其中关键语句所涉及到的对象是怎么作用的。如:
- mWorker封装任务Params,在call()方法中回调doInBackground()和onPostExecute();
- exec是类的对象(静态)sDefaultExecutor,它负责管理所有任务的执行顺序;
- mFuture封装mWorker,并作为Runnable对象被exec管理。
- 多使用快捷键进行代码跳转,比如点击鼠标中键进入方法体;用鼠标大拇指两个健控制前进和后退。
- 还有什么姿势,希望大家也能参与总结。
网友评论