首先看下AsyncTask的类:它是一个抽象类。有两个非常重要的类成员 THREAD_POOL_EXECUTOR和sDefaultExecutor 分别代表着两个线程池。 THREAD_POOL_EXECUTOR用于真正执行我们的任务,sDefaultExecutor 用于将我们的许多任务串行化一个一个的交THREAD_POOL_EXECUTOR执行。在AsyncTask类加载的过程中对他们进行实例化。
public abstract class AsyncTask<Params, Progress, Result> {
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;
}
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;//串行的线程池
//AsyncTask对象的初始状态
private volatile Status mStatus = Status.PENDING;
...
}
当我们创建AsyncTask子类对象后调用execute方法执行任务:
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
他会调用executeOnExecutor方法,在这个方法中传入了两个参数,sDefaultExecutor就是用于串行的线程池,params是我们在程序中传入的参数。继续看executeOnExecutor方法
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
//判断当前AsyncTask的状态。一个AsyncTask对象只能被执行一次,多次execute会抛异常
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)");
}
}
//将AsyncTask状态设置为Status.RUNNING
mStatus = Status.RUNNING;
//调用onPreExecute()方法,当前还是在主线程中。
//AsyncTask的实现类可以重写该方法,在执行任务前做一些准备工作
onPreExecute();
//将参数封装到mWorker中
mWorker.mParams = params;
//调用sDefaultExecutor的execute方法并将FutureTask对象传进去,该对象封装了mWorker对象
exec.execute(mFuture);
return this;
}
说明:(1)mStatus是AsyncTask类内部的一个枚举类,有三种状态:尚未执行、正在执行、执行结束。
public enum Status {
//尚未执行
PENDING,
//正在执行
RUNNING,
//执行结束
FINISHED,
}
(2)mWorker的类型是WorkerRunnable,它是一个实现了Callable接口的抽象类。在我们创建AsyncTask对象时,在AsyncTask构造方法中被实例化。并重写了call方法。mFuture的类型是FutureTask,它的内部封装了mWorker对象。
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//在这里执行任务
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
//将执行结果投递出去
postResult(result);
}
return result;
}
};
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 occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
小结:当我们调用AsyncTask对象的execute方法后,会将我们传递的参数params封装到FutureTask对象中。最后调用sDefaultExecutor的execute方法将FutureTask对象传递进去。
接着分析sDefaultExecutor的execute方法:
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
//将任务放进ArrayDeque队列中
mTasks.offer(new Runnable() {
public void run() {
try {
//调用FutureTask的run方法
r.run();
} finally {
scheduleNext();
}
}
});
//如果当前没有正在执行的任务就调用scheduleNext()
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
可以看到,当我们调用sDefaultExecutor的ececute方法并将我们的任务传进去,它会先将任务添加到mTasks队列中。如果当前没有正在执行的任务就调用scheduleNext()方法,在这个方法中取出任务然后赋给mActive变量,再将这个任务交给THREAD_POOL_EXECUTOR线程池。理解:当我们创建第一个AsyncTask并调用execute方法让他执行任务,因为此时没有任务在执行,mActive 就为空,直接调用scheduleNext方法然后将任务交给THREAD_POOL_EXECUTOR线程池处理,如果第一个任务还没有处理完,又有一个AsyncTask对象执行了execute方法,此时因为mActive不为空,就不会立即调用scheduleNext方法,只是将任务保存在mTasks中,当第一个任务执行完成,就会调用scheduleNext()方法取出第二个任务,然后再将第二个任务交给THREAD_POOL_EXECUTOR线程池处理。
从这里可以看出多个AsyncTask的任务按顺序执行就是因为sDefaultExecutor,他会将所有的任务保存在mTasks中然后每次取出一个交给THREAD_POOL_EXECUTOR线程池去处理它。
当我们将任务交给THREAD_POOL_EXECUTOR线程池去处理,他会调用FutureTask的run方法,这个方法最终调用的是WorkerRunnable的call方法:
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
//在这里执行任务
result = doInBackground(mParams);//1
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
//将执行结果投递出去
postResult(result);//2
}
return result;
}
};
可以看到注释1出就是调用我们重写的doInBackground方法,因为call方法是在线程池中被调用,所以我们的doInBackground方法也运行在非UI线程中。当doInBackground方法处理完返回结果result ,调用postResult方法,并将result作为参数传进去。
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
首先将this(当前的AsyncTask对象)和result封装到AsyncTaskResult中,然后发送给Handler处理。AsyncTaskResult类定义:
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
Handler定义如下:
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
//1
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
//2
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
当消息携带的what参数是MESSAGE_POST_RESULT时调用result.mTask的finish方法,注释2是当我们更新进度的时候调用的。
private void finish(Result result) {
if (isCancelled()) {
//如果被取消了就调用onCancelled
onCancelled(result);
} else {
//任务完成
onPostExecute(result);
}
//就当前AsyncTask对象的状态设置为Status.FINISHED
mStatus = Status.FINISHED;
}
因为handleMessage是在UI线程中被调用的,所以onPostExecute也运行在UI线程。至于为什么就确定在主线程
private static Handler getMainHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler(Looper.getMainLooper());
}
return sHandler;
}
}