AsyncTask在安卓中常用于线程间通信。在子线程执行耗时任务,在主线程更新UI。
AsyncTask内部封装了Handler和线程池。
1、AsyncTask主要靠InternalHandler去跟主线程通信,InternalHandler继承自Handler类,在handleMessage方法里面处理了消息。
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@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;
}
}
}
2、有两个线程池THREAD_POOL_EXECUTOR和SERIAL_EXECUTOR
SERIAL_EXECUTOR负责队列管理,负责执行任务的是THREAD_POOL_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);
}
}
}
回过头来,咱们再来看看executeOnExecutor方法
@MainThread
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;
}
这个方法里面做了下状态判断和状态修改,所以可以看出,一个AsyncTask实例只能执行一次。然后分别调用了onPreExecute和exec.execute(mFuture),这里的exec就是SERIAL_EXECUTOR,调用exec.execute(mFuture)就是把任务插入到任务队列中。然后依次执行任务。