近两天有点闲,在逛主席的知识星球的时候看到了AsyncTask这个知识点,在这里强烈推荐下郭婶写的AsyncTask一篇文章:https://blog.csdn.net/guolin_blog/article/details/11711405,笔者当时就是跟着这篇文章来学习AsyncTask的。今天我们一起对AsyncTask的源码进行分析下,加深下自己的理解。
照例,我们先来看下AsyncTask的定义:
private class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{
@Override //后台任务开始之前调用,进行界面初始化操作
protected void onPreExecute() {
super.onPreExecute();
}
@Override //处理耗时操作
protected Boolean doInBackground(String... params) {
return null;
}
@Override //后台任务执行完毕后回调,可进行UI操作
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
@Override //当在doInBackground方法中调用publishProgress方法后会回调该方法,执行进度更新操作
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
由于AsyncTask类是一个抽象类,所以我们需要定义一个类MyAsyncTask继承自AsyncTask,在这里需要指定三个泛型参数:第一个泛型参数为执行当前AsyncTask需要传入的参数,第二个泛型参数为进度更新的类型,第三个泛型参数为后台任务执行的返回类型。可以看到,我们重写了AsyncTask中四个常用的方法,分别为:onPreExecute、doInBackground、onPostExecute、onProgressUpdate。在上述四个方法中,除了doInBackground方法运行在工作线程,其他三个方法都是运行在UI线程中的。
接着我们就可以使用MyAsyncTask了,使用方式很简单,只需要调用execute方法即可:
new MyAsyncTask().execute("test");
关于AsyncTask的基本操作就介绍完毕了,接下来我们一起分析下AsyncTask的源码,首先看下它的构造函数:
#AsyncTask
public AsyncTask(@Nullable Looper callbackLooper) {
//1.在这里我们传入的callbackLooper为null,所以会直接调用到getMainHandler方法,
//创建InternalHandler实例sHandler,并赋值给mHandler
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
//2.创建WorkerRunnable实例对象mWorker
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);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
}
};
//3.创建 FutureTask实例mFuture,并将2处的 mWorker赋值给 mFuture对象的成员变量callable
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);
}
}
};
}
我们跟进去 1处的getMainHandler方法看下:
private static Handler getMainHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler(Looper.getMainLooper());
}
return sHandler;
}
}
可以看到,在getMainHandler方法中创建了InternalHandler实例sHandler,并绑定到UI线程。
AsyncTask的构造方法分析完毕了,我们接着从AsyncTask的入口execute方法继续分析,跟进去execute方法看下:
#AsyncTask
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
可以看到,execute方法内部直接调用到executeOnExecutor方法,将sDefaultExecutor和params参数直接传入,sDefaultExecutor是个什么东西呢?我们一起看下它的定义:
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
/**
* 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();
简单理解,sDefaultExecutor就是一个SerialExecutor实例对象,需要注意的是,该实例对象为static类型的,归属于AsyncTask类,也就是说无论我们创建多少AsyncTask实例对象,在AsyncTask类中仅存在一个SerialExecutor实例。
好了,我们回过头继续跟进去executeOnExecutor方法:
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
//1.对当前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)");
}
}
//2.将当前AsyncTask的状态标记为RUNNING
mStatus = Status.RUNNING;
//3.调用到onPreExecute方法,进行界面初始化操作
onPreExecute();
//4.将params参数赋值给mWorker的成员变量mParams
mWorker.mParams = params;
//5.调用SerialExecutor对象的execute方法,将mFuture作为参数传入
exec.execute(mFuture);
return this;
}
这里我们先来看下Status这个类,Status为枚举类,定义了AsyncTask的三种状态,分别为PENDING(初始化状态,表示当前任务还未被执行)、RUNNING(当前任务正在执行)、FINISHED(当前任务执行完毕):
/**
* Indicates the current status of the task. Each status will be set only once
* during the lifetime of a task.
*/
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,
}
好了,我们回过头继续,5处调用到SerialExecutor对象的execute方法,将mFuture作为参数传入,我们跟进去看下:
private static class SerialExecutor implements Executor {
//定义ArrayDeque队列mTasks,用于存储Runnable实例
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
//mActive表示当前正在执行的任务Runnable
Runnable mActive;
public synchronized void execute(final Runnable r) {
//1.入队操作
mTasks.offer(new Runnable() {
public void run() {
try {
//线程池中执行
r.run();
} finally {
//3.当前任务执行完毕后,则会调用scheduleNext方法执行下一项任务
scheduleNext();
}
}
});
//2.对mActive进行null判断,如果当前没有正在执行的任务,会立刻调用scheduleNext方法执行首项任务
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
SerialExecutor实现了Executor接口,该类用于串行执行任务。可以看到在SerialExecutor的execute方法中,对每一个AsyncTask对应的mFuture实例都会创建一个Runnable类型的匿名对象,并将该Runnable对象插入到mTasks队列的末尾。接着在2处对mActive进行null判断,如果当前没有正在执行的任务,会立刻调用scheduleNext方法执行首项任务。
显而易见,任务的执行重点在于scheduleNext方法,从上述代码可以看到,在scheduleNext方法中会调用mTasks.poll方法进行出队操作,删除并返回队头的Runnable对象,并将该Runnable对象赋值给mActive,如果该Runnable对象不为空,那么就将其作为参数传递给THREAD_POOL_EXECUTOR的execute方法进行执行。THREAD_POOL_EXECUTOR是个什么东西呢?那还用说吗,肯定是线程池啊:
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
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;
}
关于ThreadPoolExecutor构造方法各个参数的含义,相信大家都了解,在这里不是本文的重点,笔者就略过了。
我们回到Runnable匿名对象的run方法中看下,需要注意的是,该run方法中的所有操作均在子线程中,可以看到在Runnable对象的run方法中,直接调用到r.run()方法,大家还记得r是什么吗?r就是我们调用SerialExecutor的execute方法传入的mFuture对象(AsyncTask构造方法中对其完成的实例化)。我们跟进去看下:
#FutureTask
public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
//1.callable实质为AsyncTask构造方法中创建的mWorker对象
//在AsyncTask构造方法中创建FutureTask对象时将mWorker作为参数传入,
//赋值给FutureTask对象的callable成员变量,并将state置为NEW
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
//2.重点 调用到mWorker对象的call方法
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
我们跟进去mWorker的call方法看下:
#AsyncTask构造方法中
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
//定义Result局部变量,接收后台任务返回的结果
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//1.重点 调用到AsyncTask的doInBackground方法,执行耗时操作
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
//2.重点 调用postResult方法,将后台任务执行的结果result作为参数传入
postResult(result);
}
return result;
}
};
我们跟进去2处的postResult方法看下:
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
可以看到在postResult方法中首先将后台任务执行的结果result封装成AsyncTaskResult实例,接着通过handler发送了一条MESSAGE_POST_RESULT的Message。我们跟进去getHandler方法看下:
private Handler getHandler() {
return mHandler;
}
getHandler方法中直接将mHandler return掉了,不知道大家还记不记得,mHandler其实就是InternalHandler实例对象,在AsyncTask的构造方法中完成的赋值。好了,接下来我们看下InternalHandler的handleMessage方法:
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:
//重点,调用result.mTask.finish方法,将后台返回的result作为参数传入;result.mTask就是当前AsyncTask实例
//实质调用到当前AsyncTask对象的finish方法,将后台返回的result作为参数传入
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
//用于处理进度更新操作
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
接着我们跟进去AsyncTask的finish方法中看下:
private void finish(Result result) {
//判断当前任务是否取消
if (isCancelled()) {
//执行AsyncTask的onCancelled方法
onCancelled(result);
} else {
//执行AsyncTask的onPostExecute方法
onPostExecute(result);
}
//将当前AsyncTask的状态置为FINISHED
mStatus = Status.FINISHED;
}
到这里,AsyncTask的源码分析就结束了,希望本文可以帮助到学习AsyncTask的小伙伴。
网友评论