前言:
初学AsyncTask时,就想研究下它的实现源码,怎奈源码看了好几遍都没看懂,于是搁置了。最近心血来潮,又看了一些源码,如HandlerThread,IntentService,AsyncQueryHandler等,收获颇深,于是乎想回头再研究下AsyncTask,没想到这次居然很容易看懂了。。。
正文:
注:1.读者阅读本文前,必须对android的Handler机制以及j.u.c中的线程池有所了解;2.AsyncTask使用方式不再赘述。3.不同版本AsyncTask内容有些不同.
public abstract class AsyncTask<Params, Progress, Result>
开发者继承AsyncTask后必须重写doInbackground方法,其他方法如onPostExecute等按需重写。
AsyncTask的doInbackground中的任务就是由此线程池执行。
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
ThreadPoolExecutor各参数含义如下,CORE_POOL_SIZE为核心线程数量,MAXIMUM_POOL_SIZE为线程池最大线程数量,KEEP_ALIVE参数表明当线程池的线程数量大于核心线程数量,那么空闲时间超过KEEP_ALIVE时,超出部分的线程将被回收,sPoolWorkQueue是任务队列,存储的是一个个Runnable,sThreadFactory是线程工厂,用于创建线程池中的线程。所有这些参数在AsyncTask内部都已经定义好:
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(10);
AsyncTask并不是直接使用上述线程池,而是进行了一层“包装”,这个类就是SerialExecutor,这是个串行的线程池。
/**
* 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();
看其具体实现:
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);
}
}
}
调用execute方法时,先将Runnable包装一下(即加上try-finally块)然后加入队列,接着判断当前mActive是否为空,第一次调用,此值为空,所以会调用scheduleNext方法,从队列中取出头部的任务,交给线程池THREAD_POOL_EXECUTOR处理,而处理过程是这样的,先执行原先的Runnable的run方法,接着再执行scheduleNext从队列中取出Runnable,如此循环,直到队列为空,mActive重新为空为止。我们发现,经过这样的处理, 所有任务将串行执行。
所以我们需要注意,如果两个AsyncTask都调用execute时,如果其中一个AsyncTask任务执行时间非常长,这将导致另一个AsyncTask的任务排队等候,无法执行,因为它们共享同一个线程池且池是串行执行任务的。
接着看其他成员:
private static final int MESSAGE_POST_RESULT = 0x1;//当前消息类型--->任务完成消息
private static final int MESSAGE_POST_PROGRESS = 0x2;//当前消息类型-->进度消息
private static final InternalHandler sHandler = new InternalHandler();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;//默认线程池
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
private volatile Status mStatus = Status.PENDING;//当前状态
private final AtomicBoolean mCancelled = new AtomicBoolean();
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
sDefaultExecutor指明默认的线程池是串行池,mStatus指明当前任务状态,Status是个枚举类型:
public enum Status {
/**
* Indicates that the task has not been executed yet.
*/
PENDING,//等待执行
/**
* Indicates that the task is running.
*/
RUNNING,//执行
/**
* Indicates that {@link AsyncTask#onPostExecute} has finished.
*/
FINISHED,//执行结束
}
重点看InternalHandler实现:
private static class InternalHandler extends Handler {
@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;
}
}
}
InternalHandler继承自Handler,并复写了handleMessage,该方法根据消息类型做不同处理,
如果任务完成,则调用finish方法,而finish方法根据任务状态(取消or完成)调用onCancelled或者onPostExecute,这两个是回调方法,通常我们会在onPostExecute中根据任务执行结果更新UI,这也是为什么文档中要求AsyncTask必须在UI线程中创建的原因,我们的Handler须与UI线程的Looper绑定才能更新UI,并且子线程默认是没有Looper的。
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
如果是更新进度的消息(MESSAGE_POST_PROGRESS),那么调用onProgressUpdate方法。
doInbackground方法在何处被调用?联想AsyncTask的使用,当我们创建好一个AsyncTask实例后,我们将调用其execute方法,所以,doInbackground方法应该在execute方法中执行,找到其实现:
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
并没有直接调用doInbackground,而是调用了executeOnExecutor方法:
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;
}
executeOnExecutor方法的作用是使用指定的线程池执行任务,这里当然使用的是sDefaultExecutor,也就是SerialExecutor,但是我们注意到这个方法是公共的,也就是说 我们可以手动配置线程池,让AsyncTask并行执行起来,最简单的方法就是使用内部定义好的THREAD_POOL_EXECUTOR。
executeOnExecutor方法首先检查当前状态,如果不是Pending状态则抛出异常,紧接着修改状态为Running态,接着调用onPreExecute方法(预处理,相信大家不陌生)。
关键代码是exec.execute(mFuture)这一句,这行代码的作用是执行mFuture中定义好的任务,mFuture为FutureTask类型,FutureTask是Runnable的实现类(j.u.c中的),所以可以作为线程池execute方法的参数,我们找到其定义:
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);
}
}
};
我们都知道,FutureTask构造时必须传入一个Callable的实现类,线程最终执行的是Callable的call方法(不明白的请看java线程并发库),所以mWorker必然是Callable的实现类:
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
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));
}
};
最终,我们在WorkRunnable方法中找到了doInBackground方法,历经艰辛啊!!
剩下最后一个问题: 消息是如何发送给Handler的?
1.任务执行完毕的消息是通过postResult方法发送的:
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
这个AsyncTaskResult封装了数据域和对象本身:
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
2.任务进度更新消息是通过publishProgress方法发送的:
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
至此,AsyncTask源码分析完毕!
稍微做个 总结:
1.AsyncTask是对线程池和Handler的封装,但是默认情况下任务是串行执行的,需注意,多个AsyncTask实例共享同一线程池(线程池是static的);
2.高并发任务并不推荐使用AsyncTask,而应该改用线程池;
3.务必在主线程中创建AsyncTask,因为AsyncTask内部的Handler在创建时必须要绑定主线程的Looper;
4.只能在doInBackground方法中执行耗时任务,其他方法如onPreExecute、onPostExecute等运行于主线程上.