【AsyncTask 源码解析】本文基于SDK Android-29 AsyncTask.java
从execute方法开始分析,execute方法会调用executeOnExecutor方法
sDefaultExecutor是一个串行的线程池,一个进程中所有的AsyncTask都会在sDefaultExecutor中排队执行。
@MainThread
public final AsyncTask execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
在executeOnExecutor方法中onPreExecute方法最先执行,然后线程池开始执行。
@MainThread
public final AsyncTask 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;
}
下面分析线程池的执行过程。
/**
* An {@link Executor} that executes tasks one at a time in serial
* order.This serialization is global to a particular process.
*/
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
@UnsupportedAppUsage
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
private static class SerialExecutor implements Executor {
final ArrayDeque mTasks = new ArrayDeque();
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);
}
}
}
系统首先会把AsyncTask的Params参数封装为FutureTask对象,FutureTask是一个并发类,在这里他充当了Runnable的作用。
接着FutureTask会交给SerialExecutor的execute方法处理,SerialExecutor的execute方法首先会把FutureTask对象插入到任务队列mTasks中,如果这个时候没有正在活动的AsyncTask任务,那么就会调用SerialExecutor的scheduleNext方法来执行下一个AsyncTask任务。
同时当一个AsyncTask任务执行完后,AsyncTask会继续执行其他任务直到所有的任务都被执行为止,从这一点可以看出,在默认情况下,AsyncTask是串行执行的。
AsyncTask中有两个线程池(SerialExecutor和THREAD_POOL_EXECUTOR)和一个Handler(InternalHandler),其中线程池SerialExecutor用于任务的排队,而线程池THREAD_POOL_EXECUTOR用于真正执行任务,InternalHandler用于将执行环境从线程池切换到主线程,其本质仍然是线程的调用过程。由于FutureTask的run方法会调用mWorker的call方法,因此mWorker的call方法最终会在线程池中执行。
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
}
};
在mWorker的call方法中,首先将mTaskInvoked设置为true,表示当前任务已经被调用过了,然后执行AsyncTask的doInBackground方法,接着将其返回值传递给postResult方法,它的实现如下所示。
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
在上面的代码中,postResult方法会通过getHandler方法获取mHandler发送一个MESSAGE_POST_RESULT的消息,这个mHandler的定义如下所示。判断callbackLooper的值等于空(初始化)或者程序主循环,sHandler赋值给callbackLooper,否则新建Handler赋值给callbackLooper,它的实现如下所示。
private final Handler mHandler;
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
...
}
Looper.java
/**
* Returns the application's main looper, which lives in the main thread of the application.
*/
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
private static InternalHandler sHandler;
private static Handler getMainHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler(Looper.getMainLooper());
}
return sHandler;
}
}
可以发现,sHandler是一个静态的Handler对象,为了能够将执行环境切换到主线程,这就要求sHandler这个对象必须在主线程中创建。由于静态成员会在加载类的时候进行初始化,因此这就变相要求AsyncTask的类必须在主线程中加载,否则同一个进程中的AsyncTask都将无法正常工作。此处sHandler使用单例模式初始化。
private static class InternalHandler extends Handler {
public InternalHandler(Looper looper) {
super(looper);
}@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult> result = (AsyncTaskResult>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = https://www.it610.com/article/data;
}
}
sHandler在收到MESSAGE_POST_RESULT这个消息后会调用AsyncTaskResult的mTask的finish方法,如下所示。
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
AsyncTask的finish方法的逻辑比较简单,如果AsyncTask被取消执行了,那么就调用onCancelled方法,否则就会调用onPostExecute方法,可以看到doInBackground方法的返回结果会传递给onPostExecute方法,到这里AsyncTask的整个工作流程就分析完毕了。
文章摘自Android艺术开发探索.