写在前面的话
上一篇我们讲到了Android多线程之Handler,即Handler与Thread共同使用进行的多线程编程。
但是,Handler模式下,我们需要为每一个任务都创建一个新的线程,任务完成后向UI线程发送消息并在UI线程进行UI的更新。
这对于多个任务来说,创建与销毁进程的开销就会很大。
从Android1.5开始,提供了AsyncTask,将Handler与线程池封装在一起,使得创建异步任务更加简化。
AsyncTask内部包含了一个Handler,可以发送消息给UI线程,正因为如此,AsyncTask的实例必须在UI线程进行创建且调用execute方法。
AsyncTask内还包含了一个线程池,用来维护固定数量的线程,避免不必要的创建及销毁线程的开销。
AsyncTask使用简介
我们来看一下AsyncTask的声明:
public abstract class AsyncTask<Params, Progress, Result> {
AsyncTask是一个抽象类,也是一个泛型类,它的三个参数类型含义如下:
Params 任务实例执行的方法execute(Params... params)的参数类型和doInBackground(Params... params)方法的参数类型;
Progress 执行的后台任务的进度类型,即onProgressUpdate(Progress... values)方法的参数类型;
Result 后台任务的返回结果类型,即doInBackground(Params... params)的返回类型和onPostExecute(Result result)的参数类型。
继承AsyncTask一般需要重写的方法:
onPreExecute() //非必须重写,在doInBackground方法执行前调用,用于进行一些准备工作
doInBackground(Params... params) //必须重写,要执行的后台任务,其间可调用publishProgress来更新任务进度(publishProgress方法进而调用onProgressUpdate方法)
onProgressUpdate(Progress... values) //非必须重写,由publishProgress方法内部调用,表示任务进度更新
onPostExecute(Result result) //非必须重写,doInBackground方法执行完毕后调用,参数即为后台任务的返回结果
onCancelled() //非必须重写,在后台任务被取消时被调用
其实例执行任务的方法有两种:
public final AsyncTask<Params, Progress, Result> execute(Params... params)
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params)
我们来看一个简单的例子:
public class AsyncTaskTestActivity extends BaseActivity {
private static final String TAG = "AsyncTaskTestActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_empty);
new DownloadTask().execute("Input");
}
private static class DownloadTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.i(TAG, "onPreExecute");
}
@Override
protected String doInBackground(String... params) {//后台任务,一般为耗时操作
Log.i(TAG, "doInBackground: params is " + params[0]);
String result = "";
if (params[0].equals("Input")) {
result = "Output";
}
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i(TAG, "onPostExecute: result is " + s);
}
}
}
打印结果:
I/AsyncTaskTestActivity: onPreExecute
I/AsyncTaskTestActivity: doInBackground: params is Input
I/AsyncTaskTestActivity: onPostExecute: result is Output
1. 创建DownloadTask,继承自AsyncTask,三个参数类型分别为String、Integer、String
2. 实现doInBackground方法,这是必须实现的方法,参数String类型即为执行后台任务需要用到的参数类型
3. 重写onPreExecute方法,一般会在这里执行一些准备工作,因为这个方法在doInBackground方法之前执行
4. 重写onPostExecute方法,参数类型是String,参数s就是doInBackground方法返回的result,doInBackground执行完毕后将结果返回给onPostExecute方法作为参数
5. 执行这个任务实例,new DownloadTask().execute("Input"),执行这个方法后,会将“Input”这个参数传给doInBackground作为参数
一般执行顺序:
execute -> onPreExecute -> doInBackground( -> publishProgress -> onProgressUpdate) -> onPostExecute
解读AsyncTask源码
我们先来看一下AsyncTask.java中的关于任务生命周期中存在的状态,类中定义了一个枚举类Status,任务的初始状态是PENDING:
/**
* 指示任务的当前状态. 每个任务的生命周期过程中,下面的三种状态只能被设置一次.
*/
public enum Status {
/**
* 任务还未开始执行.
*/
PENDING,
/**
* 任务在运行中.
*/
RUNNING,
/**
* onPostExecute方法已经完成,任务执行完毕.
*/
FINISHED,
}
我们从
execute(Params... params)方法入手,来看看执行过程:
/**
* Executes the task with the specified parameters. The task returns itself (this) so that the caller can keep a reference to it.
* 按照指定的参数执行任务。任务执行完会返回它自己以便于调用者能够拿到任务的引用。
*
* Note: this function schedules the task on a queue for a single background thread or pool of threads depending on the platform version.
* 任务执行时,是在一个后台线程的队列还是一个线程池,取决于platform的版本号。
*
* When first introduced, AsyncTasks were executed serially on a single background thread.
* 首次介绍时,AsyncTasks在后台线程里被串行执行。
*
* Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed to a pool of threads allowing multiple tasks to operate in parallel.
* 从Android1.6开始,变成了线程池并允许多个任务并行执行。
*
* 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.
* 从Android3.0开始,任务又变回了串行执行,以避免并行执行时发生的错误。
*
* If you truly want parallel execution, you can use the {@link #executeOnExecutor} version of this method with {@link #THREAD_POOL_EXECUTOR};
* 如果你还是想用并行执行,可以使用executeOnExecutor方法,同时使用THREAD_POOL_EXECUTOR线程池。
*
* however, see commentary there for warnings on its use.
*
* This method must be invoked on the UI thread.
* 这个方法必须在UI线程调用。
*
* @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);
}
可以看出,实际上execute方法将executeOnExecutor方法的返回结果作为结果进行返回。
注意点:execute方法必须在UI线程执行。
我们来看一下executeOnExecutor(Executor exec, Params... params)方法:
/**
* 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.
* 这个方法与THREAD_POOL_EXECUTOR一起,用来允许多任务在线程池里并行执行;当然也可以使用自定义的Executor。
*
* Warning: 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}.
* 这种情况下最好还是串行执行,可以用这个方法配合SERIAL_EXECUTOR使用
*
* @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.
*/
@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;
}
注意点:
依旧要在UI线程执行;配合THREAD_POOL_EXECUTOR进行并行执行;配合SERIAL_EXECUTOR进行串行执行。
那我们回头看一下execute方法将sDefaultExecutor传给executeOnExecutor,那sDefaultExecutor是什么呢?
/**
* 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 volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
可以看到,sDefaultExecutor是
SerialExecutor的实例,所以说,默认AsyncTask的执行是串行的。
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);
}
}
}
注意看SerialExecutor类,mTasks表示串行线程池的任务缓存队列。
SerialExecutor的实例执行execute(final Runnable r)方法时,用offer方法向任务缓存队列中添加一个任务,然后会调用 r.run() 方法。
这个r.run() 方法其实就是mFuture的run()方法[FutureTask中的run()方法],最后会调用mWorker的call()方法,我们后面再介绍这个。
executeOnExecutor方法中有两行代码 mWorker.mParams = params; exec.execute(mFuture);
params是我们传入的指定的参数,exec是sDefaultExecutor。那 mWorker.mParams 和 mFuture 是什么呢?
先来看一下AsyncTask初始化的时候做了什么
public AsyncTask() {
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;
}
};
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);
}
}
};
}
看一下mWorker:
private final WorkerRunnable<Params, Result> mWorker;
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
mWorker是WorkRunnable类的对象。WorkRunnable是一个抽象类,它实现了Callable<Result>接口。
所以 mWorker.mParams = params; 就是将我们指定的params传给了mWorker的成员mParams。
再来看 mFuture:
private final FutureTask<Result> mFuture;
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
mFuture是一个FutureTask的直接子类(匿名内部类)的对象,在FutureTask的构造方法中我们传入了mWorker作为参数。
注意到,FutureTask的构造方法将callable,即mWorker传进来赋给this.callable。
所以,当mFuture的run()方法执行时,就会执行FutureTask中的run()方法,下面的源码 result = c.call() , 就是mWorker的call()方法啦。
public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
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);
}
}
所以,默认情况下 exec.execute(mFuture) 执行时,
--->会执行SerialExecutor中重写的execute(final Runnable r)方法,
--->进而执行mFuture的run()方法[就是FutureTask中的run()方法],
--->然后调用mWorker的call()方法。
call()方法中,首先将mTaskInvoked设为true表示当前任务已被调用过,然后设置线程的优先级为后台线程。
然后调用了doInBackground方法执行后台任务,并将任务返回结果传递给postResult方法进行返回。
我们来看看postResult(Result result)方法:
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
创建Handler对象时需要Handler所在线程的Looper,所以为了能够通过sHandler将执行环境从后台线程切换到主线程(即在主线程中执行handleMessage方法),
必须使用主线程的Looper,因此必须在主线程中创建sHandler。这也就解释了为什么必须在主线程中创建AsyncTask类的实例。
调用getHandler()获取AsyncTask对象内部包含的sHandler,然后发送了MESSAGE_POST_RESULT消息。
看看InternalHandler中重写的handlerMessage(Message msg)方法:
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;
}
}
}
当sHandler收到MESSAGE_POST_RESULT方法后,会调用finish方法,如下:
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
调用isCancelled方法判断AsyncTask任务是否被取消,若取消了则调用onCancelled(Result result)方法;
否则调用onPostExecute(Result result)方法;
最后把mStatus设为FINISHED,表示当前AsyncTask对象已经执行完毕。
执行流程总结
所以我们来总结一下整个执行流程:
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;//将任务状态置为RUNNING运行中
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
1. 实例的execute(Params... params)方法执行后,首先将任务状态置为RUNNING;随后调用onPreExecute()方法
2. mWorker接收到参数以后,exec(即sDefaultExecutor)调用SerialExecutor中重写的execute(final Runnable r)方法
3. 进而执行mFuture的run()方法[会执行FutureTask中的run()方法],进一步调用mWorker的call()方法
4. call()方法调用了doInBackground方法返回结果,并利用postResult方法发送MESSAGE_POST_RESULT消息给内部sHandler
5. sHandler接收MESSAGE_POST_RESULT消息后,调用finish方法,进而调用onPostExecute方法,并将任务状态设置为FINISHED
其他注意点
1. publishProgress方法
我们前面说到在doInBackground方法中,可以调用publishProgress方法进行对进度的更新:
/**
* This method can be invoked from {@link #doInBackground} to publish updates on the UI thread
* while the background computation is still running.
* 当后台任务还在运行时,可以在doInBackground方法中调用这个方法来更新UI线程的进度。
*
* Each call to this method will trigger the execution of {@link #onProgressUpdate} on the UI thread.
* 每次调用这个方法都会触发UI线程中的onProgressUpdate方法的执行。
*
* {@link #onProgressUpdate} will not be called if the task has been canceled.
* 如果task被取消,则不会执行这个方法
*
* @param values The progress values to update the UI with.
*/
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
可以看到,当在doInBackground方法中调用这个方法时,sHandler会发送
MESSAGE_POST_PROGRESS,我们上面讲到的在InternalHandler中:
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
证明是会执行AsyncTask中的onProgressUpdate方法。
2. 并行执行
上面讲到并行执行时要使用executeOnExecutor方法,并传入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的各个参数:
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
// We want at least 2 threads and at most 4 threads in the core pool,
// preferring to have 1 less than the CPU count to avoid saturating
// the CPU with background work
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE_SECONDS = 30;
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>(128);
CORE_POOL_SIZE:最少2个,最多4个
MAXIMUM_POOL_SIZE:最少1个
KEEP_ALIVE_SECONDS:30秒
sPoolWorkQueue:任务缓存队列为LinkedBlockingQueue
参考链接