做Android开发的肯定有用到AsyncTask这个类,对于执行耗时操作+更新UI这个业务很有效,它内部使用一个线程池,串行执行每一个线程,线程生命周期不用你自己管理,想要异步处理的东西往里扔就行了,而且doInBackground执行完的结果可以直接在onPostExecute方法参数里得到,直接更新UI界面。
这一套业务也可以使用Thread来做,但是使用Thread有些麻烦,每次使用都要自己new一个线程,要自己管理其生命周期,而且android还不允许在非主线程的线程更新UI,这样的话thread运行得到的结果如果需要更新UI可能还需要发一个handler通知主线程更新界面,代码写起来比较凌乱不如asynctask一目了然好维护。
AsyncTask的使用比较简单,这里就不多说了,今天主要分析下AsyncTask的源码,看看Google是怎么设计这种业务的。
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
//获取CPU数量
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//确定线程池核心线程数量
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
//确定线程池线程最大数量
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
//线程工厂,下面实例化线程池要使用
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
//提供原子操作的Integer类,确保getAndIncrement()线程安全
private final AtomicInteger mCount = new AtomicInteger(1);
//重写该方法,确定新增加的线程的线程名,就是增加一个标识,表明这个线程是AsyncTask的
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
/**
* BlockingQueue 是Concurrent包中的一种阻塞队列
* 当BlockingQueue为空, 从队列取数据时会让线程等待状态,直到能取出非空的数据,线程会被唤醒。
* 当BlockingQueue是满的,存数据到队列时线程也会进入等待状态,直到有空间,线程才会被唤醒。
* 在这里是存放待执行的Runnable,容量为128
*/
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
/**
* An {@link Executor} that can be used to execute tasks in parallel.
* 根据上面的参数实例化线程池
*/
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
/**
* An {@link Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
* AsyncTask内部实现的线程池,串行执行线程
*/
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
/**
* Handler消息的what
*/
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
//用原子符修饰sDefaultExecutor,并且将SERIAL_EXECUTOR赋值给sDefaultExecutor
//AsyncTask内部使用它进行执行任务
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
//主线程的Handler
private static InternalHandler sHandler;
/**
* AstncTask内部类,实现了Callable接口
* 内部实例了一个保存参数的mParams数组
* Callable接口内部有一个call方法,方法里是开发者具体逻辑实现,与Runnable接口类似,
* 只不过Runnable里的run方法没有返回值,而call方法有返回值
*/
private final WorkerRunnable<Params, Result> mWorker;
/**
* FutureTask类实现了Runnable接口和Future接口,且内部维护了一个Callable对象,
* FutureTask的构造函数中需要传入一个Callable对象以对其进行实例化
* Executor的execute方法接收一个Runnable对象,由于FutureTask实现了Runnable接口,
* 所以可以把一个FutureTask对象传递给Executor的execute方法去执行。
* 当任务执行完毕的时候会执行FutureTask的done方法,我们可以在这个方法中写一些逻辑处理。
* 在任务执行的过程中,我们也可以随时调用FutureTask的cancel方法取消执行任务,任务取消后也会执行FutureTask的done方法。
* 我们也可以通过FutureTask的get方法阻塞式地等待任务的返回值(即Callable的call方法的返回值),
* 如果任务执行完了就立即返回执行的结果,否则就阻塞式等待call方法的完成。
*/
private final FutureTask<Result> mFuture;
//标识当前正在执行的线程的状态
private volatile Status mStatus = Status.PENDING;
/**
* 提供原子操作的Boolean类型,保证线程安全
* mCancelled表示任务是否被取消
* mTaskInvoked是否开始执行了
*/
private final AtomicBoolean mCancelled = new AtomicBoolean();
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
/**
* 自定义一个线程池,串行执行任务
* 串行执行逻辑就是:
* 首先通过execute(Params... params)方法执行到这个类的execute;
* 然后将mFuture封装成一个Runnable(里面的run方法的逻辑就是先执行mFuture的run方法,
* 执行结束后就通过scheduleNext()方法取出下一个任务执行,循环往复)添加到队列里;
* 但是一开始mActive肯定为null,所以就通过scheduleNext()方法取出上一步添加的任务去执行;
* 以后就循环执行run方法里的逻辑
*/
private static class SerialExecutor implements Executor {
/**
* ArrayDeque是一个双向队列,能够同时在两端进行插入删除操作,
* 不过它的内部没有做同步操作,虽然效率上要高于linkedList, vector等,但是存在并发问题
* 需要开发者自己做维护,这里SerialExecutor就是串行执行,所以没有并发问题
* 在这里存放Runnable,队列容量没有限制
*/
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
//当前正在执行的任务
Runnable mActive;
//实现Executor的execute方法,用于串行执行任务
public synchronized void execute(final Runnable r) {
//通过队列的offer方法将封装后的r添加到队列的最后
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
//r执行结束后执行下一个任务
scheduleNext();
}
}
});
//当前没有执行任务,就执行这个方法去取任务执行
if (mActive == null) {
scheduleNext();
}
}
//返回并删除队列的头部第一个元素,然后把线程交给线程池执行
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
/**
* 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,
}
//获取Handler
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
/** @hide */
public static void setDefaultExecutor(Executor exec) {
sDefaultExecutor = exec;
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
//实例化mWorker对象,
mWorker = new WorkerRunnable<Params, Result>() {
//实现call方法,执行任务
public Result call() throws Exception {
//将mTaskInvoked设置为true,表明任务开始执行
mTaskInvoked.set(true);
//将该线程设置为后台线程
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//这个方法就是我们具体逻辑的实现,然后获取返回结果
Result result = doInBackground(mParams);
Binder.flushPendingCommands();
//将返回结果传递给postResult
return postResult(result);
}
};
//当mFuture被sDefaultExecutor执行的时候,FutureTask内部run方法中的callable对象会调用call方法,
// 就会走到上面的mWorker对象的call方法,方法走完,FutureTask内部run方法中会调用set(result)方法或者setException(ex)方法
// 这两个方法里都会回调done()方法。
mFuture = new FutureTask<Result>(mWorker) {
//任务执行结束或者被取消都会调用done方法
@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);
}
}
};
}
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
//call方法没有被调用执行这个
postResult(result);
}
}
/**
* AsyncTaskResult是一个内部类,里面包含执行任务的AsyncTask对象和返回的数据
* 将结果封装到AsyncTaskResultHandler中发送出去
* @param result
* @return
*/
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
/**
* Returns the current status of this task.
*
* @return The current status.
*/
public final Status getStatus() {
return mStatus;
}
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
*
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
*
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
@WorkerThread
protected abstract Result doInBackground(Params... params);
/**
* Runs on the UI thread before {@link #doInBackground}.
*
* @see #onPostExecute
* @see #doInBackground
*/
@MainThread
protected void onPreExecute() {
}
/**
* <p>Runs on the UI thread after {@link #doInBackground}. The
* specified result is the value returned by {@link #doInBackground}.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* @param result The result of the operation computed by {@link #doInBackground}.
*
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onPostExecute(Result result) {
}
/**
* Runs on the UI thread after {@link #publishProgress} is invoked.
* The specified values are the values passed to {@link #publishProgress}.
*
* @param values The values indicating progress.
*
* @see #publishProgress
* @see #doInBackground
*/
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onProgressUpdate(Progress... values) {
}
/**
* <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
* {@link #doInBackground(Object[])} has finished.</p>
*
* <p>The default implementation simply invokes {@link #onCancelled()} and
* ignores the result. If you write your own implementation, do not call
* <code>super.onCancelled(result)</code>.</p>
*
* @param result The result, if any, computed in
* {@link #doInBackground(Object[])}, can be null
*
* @see #cancel(boolean)
* @see #isCancelled()
*/
@SuppressWarnings({"UnusedParameters"})
@MainThread
protected void onCancelled(Result result) {
onCancelled();
}
/**
* <p>Applications should preferably override {@link #onCancelled(Object)}.
* This method is invoked by the default implementation of
* {@link #onCancelled(Object)}.</p>
*
* <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
* {@link #doInBackground(Object[])} has finished.</p>
*
* @see #onCancelled(Object)
* @see #cancel(boolean)
* @see #isCancelled()
*/
@MainThread
protected void onCancelled() {
}
/**
* Returns <tt>true</tt> if this task was cancelled before it completed
* normally. If you are calling {@link #cancel(boolean)} on the task,
* the value returned by this method should be checked periodically from
* {@link #doInBackground(Object[])} to end the task as soon as possible.
*
* @return <tt>true</tt> if task was cancelled before it completed
*
* @see #cancel(boolean)
*/
public final boolean isCancelled() {
return mCancelled.get();
}
/**
* <p>Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, already been cancelled,
* or could not be cancelled for some other reason. If successful,
* and this task has not started when <tt>cancel</tt> is called,
* this task should never run. If the task has already started,
* then the <tt>mayInterruptIfRunning</tt> parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.</p>
*
* <p>Calling this method will result in {@link #onCancelled(Object)} being
* invoked on the UI thread after {@link #doInBackground(Object[])}
* returns. Calling this method guarantees that {@link #onPostExecute(Object)}
* is never invoked. After invoking this method, you should check the
* value returned by {@link #isCancelled()} periodically from
* {@link #doInBackground(Object[])} to finish the task as early as
* possible.</p>
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete.
*
* @return <tt>false</tt> if the task could not be cancelled,
* typically because it has already completed normally;
* <tt>true</tt> otherwise
*
* @see #isCancelled()
* @see #onCancelled(Object)
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
mCancelled.set(true);
return mFuture.cancel(mayInterruptIfRunning);
}
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return The computed result.
*
* @throws CancellationException If the computation was cancelled.
* @throws ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
*/
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result.
*
* @param timeout Time to wait before cancelling the operation.
* @param unit The time unit for the timeout.
*
* @return The computed result.
*
* @throws CancellationException If the computation was cancelled.
* @throws ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
* @throws TimeoutException If the wait timed out.
*/
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return mFuture.get(timeout, unit);
}
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* <p>Note: this function schedules the task on a queue for a single background
* thread or pool of threads depending on the platform version. When first
* introduced, AsyncTasks were executed serially on a single background thread.
* Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
* to a pool of threads allowing multiple tasks to operate in parallel. Starting
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
* executed on a single thread to avoid common application errors caused
* by parallel execution. If you truly want parallel execution, you can use
* the {@link #executeOnExecutor} version of this method
* with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
* on its use.
*
* <p>This method must be invoked on the UI thread.
*
* @param params The parameters of the task.
*
* @return This instance of AsyncTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
*
* @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
* @see #execute(Runnable)
*/
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
* allow multiple tasks to run in parallel on a pool of threads managed by
* AsyncTask, however you can also use your own {@link Executor} for custom
* behavior.
*
* <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
* a thread pool is generally <em>not</em> what one wants, because the order
* of their operation is not defined. For example, if these tasks are used
* to modify any state in common (such as writing a file due to a button click),
* there are no guarantees on the order of the modifications.
* Without careful work it is possible in rare cases for the newer version
* of the data to be over-written by an older one, leading to obscure data
* loss and stability issues. Such changes are best
* executed in serial; to guarantee such work is serialized regardless of
* platform version you can use this function with {@link #SERIAL_EXECUTOR}.
*
* <p>This method must be invoked on the UI thread.
*
* @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a
* convenient process-wide thread pool for tasks that are loosely coupled.
* @param params The parameters of the task.
*
* @return This instance of AsyncTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
*
* @see #execute(Object[])
*/
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
//如果这个AsyncTask已经执行了还执行这个方法就抛出异常
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
//如果这个AsyncTask已经执行结束了还执行这个方法就抛出异常
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
//将该任务标识为正在执行
mStatus = Status.RUNNING;
//回调该方法,开发者可在这个方法里做一些准备工作
onPreExecute();
//将开发者传入的参数赋值给mWorker对象的内部变量
mWorker.mParams = params;
//让sDefaultExecutor执行mFuture,其实就是SerialExecutor这个类去执行execute(final Runnable r)方法,
//因为mFuture实现了Runnable接口,所以线程池可以执行这个对象
exec.execute(mFuture);
return this;
}
/**
* Convenience version of {@link #execute(Object...)} for use with
* a simple Runnable object. See {@link #execute(Object[])} for more
* information on the order of execution.
*
* @see #execute(Object[])
* @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
*/
@MainThread
public static void execute(Runnable runnable) {
sDefaultExecutor.execute(runnable);
}
/**
* This method can be invoked from {@link #doInBackground} to
* publish updates on the UI thread while the background computation is
* still running. Each call to this method will trigger the execution of
* {@link #onProgressUpdate} on the UI thread.
*
* {@link #onProgressUpdate} will not be called if the task has been
* canceled.
*
* @param values The progress values to update the UI with.
*
* @see #onProgressUpdate
* @see #doInBackground
*/
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
private void finish(Result result) {
if (isCancelled()) {
//如果任务被取消了,回调该方法
onCancelled(result);
} else {
//如果任务正常走完,就回调该方法
onPostExecute(result);
}
//将该任务状态设置为结束
mStatus = Status.FINISHED;
}
private static class InternalHandler extends Handler {
public InternalHandler() {
//获取主线程的Looper,将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:
//开发者通过调用publishProgress,会转到这里将过程回调给开发者
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
/**
* 将AsyncTask和返回数据封装成一个对象,用于Handler通信时使用
* @param <Data>
*/
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
//具体执行任务的AsyncTask
final AsyncTask mTask;
//存储数据,一个可变长度的数组
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
具体什么意思已经注释了,很清楚,那大概整理下流程,从代码的上面开始往下看
* 获取cpu数量,核心线程数量,线程池最大线程数量,实例化了一个线程工厂(标识新线程的名称),一个
存放线程池的阻塞队列,最后构建一个线程池,这些东西都是静态的,不会每次new Asynctask都会实例化
* AsyncTask内部自己实现了一个线程池SerialExecutor类,从这个名字也可以看出来,这是一个串行执行器,
平时看到很多分析博客还在说AsyncTask可以同时运行多个线程,其实这是不对的,只有老早的版本才会这样。
至于串行的实现原理,上面注释已经很清楚了。之后把这个类的引用赋值给sDefaultExecutor
* 接下来就是AsyncTask构造方法了,做了两件事,第一件就是实例化了一个WorkerRunnable对象,它是内部
类,实现了Callable接口,并且定义了一个存放开发者传入的参数的数组,重写了call方法,这里就是耗时
操作的执行地,并且将执行结果返回,最终会回调到onPostExecute(Result result);第二件事就是实例化
一个FutureTask对象,重写done方法,当任务执行结束或者出现异常会回调这个方法。
* 最后就是两个最重要的方法了,开发者new了一个AsyncTask对象后调用它的execute(Params... params)方法,
这里走到了executeOnExecutor(Executor exec,Params... params)方法,第一个参数是sDefaultExecutor,也就是
SerialExecutor对象,第二个参数是开发者传入的参数。异步任务运行逻辑将FutureTask丢到SerialExecutor的类
的execute方法中,这个方法将FutureTask又封装成了一个Runnable,这个Runnable的run方法逻辑就是执行
FutureTask的run方法(这里面会回调WorkerRunnable的call方法,这里面会回调doInBackground;执行完毕后
调用FutureTask的done方法),执行结束后调用scheduleNext()方法循环往复。
到此,AsyncTask的源码就这样分析结束。