AsyncTask源码的理解
介绍
AsyncTask是Android中已经封装好的,用于子线程操作的类。实现的主要方式仍然是Android中熟悉的Thread+Handler模式,
最终以模板的形式让程序员使用。如果同一时间多次使用AsyncTask去执行任务,
默认情况下,这些子线程会按照FIFO的顺序执行,不会并发执行。
执行流程
只是给出了大概的流程,细节的地方(比如onProgressUpdate()等)没有提到,面面俱到的话会影响到对主要流程的把控。
相关代码的注释
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
/*以下是为了配置THREAD_POOL_EXECUTOR中的参数*/
//CPU的核数
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//根据CPU的核数来动态的计算线程池的核心线程的个数
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
//根据CPU的核数来动态的计算线程池的最大线程的个数
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
//获取队列中任务的超时时间,当阈值时间内无法获取线程,则会销毁处理线程,前提是线程数量在corePoolSize 以上
执行队列
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>(128);
/*以上是为了配置THREAD_POOL_EXECUTOR中的参数*/
//正真用来执行线程的的Executor,默认情况下与SERIAL_EXECUTOR配合使用
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
//默认情况下与THREAD_POOL_EXECUTOR配合使用,是线程成“串行”的方式来执行,也就是一个线程执行完毕后,才会执行下一个
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
//用户Handler发送消息的标识
//通知线程运行的结果
private static final int MESSAGE_POST_RESULT = 0x1;
//通知线程运行的进度
private static final int MESSAGE_POST_PROGRESS = 0x2;
//默认的Executor,是SERIAL_EXECUTOR,在多线程的情况下,是各个线程按FIFO串行
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
//用来通知UI线程的Handler
private static InternalHandler sHandler;
//与mFuture配合使用,doInBackground()在这里执行
private final WorkerRunnable<Params, Result> mWorker;
//与mWorker配合使用,doInBackground()在这里执行
private final FutureTask<Result> mFuture;
//标识状态
private volatile Status mStatus = Status.PENDING;
//状态,取消
private final AtomicBoolean mCancelled = new AtomicBoolean();
//状态,执行
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
//自定义execute()方法,通过队列的方式来依次执行队列中的子线程,这是保证AsyncTask中线程不会并发进行
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
//逻辑:1.往队列里添加子线程,没有对mActive进行赋值
//2.mActive为空,执行了scheduleNext()方法
//3.scheduleNext()中,从队列中取第一个线程来执行
//4.执行完毕后,finally中,再次调用scheduleNext(),如果有新的子线程添加进来,继续执行队列中的头一个子线程,直到队列为空
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) {
//这里可以看出,真正执行子线程的Executor是THREAD_POOL_EXECUTOR
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
//用来表标识状态
public enum Status {
//挂起
PENDING,
//运行
RUNNING,
//结束
FINISHED,
}
//获取Handler
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
//如果不想串行,可以自定义Executor,不建议这样做
/** @hide */
public static void setDefaultExecutor(Executor exec) {
sDefaultExecutor = exec;
}
//可以看出,在构造方法中,创建了mWorker和mFuture这两个对象
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
//标识子线程调用了
mTaskInvoked.set(true);
//设置优先级,可以不考虑
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//doInBackground()调用的地方
//noinspection unchecked
Result result = doInBackground(mParams);
//系统的操作,不用管
Binder.flushPendingCommands();
//给Handler发送消息
return postResult(result);
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
//mWorker执行完毕后,会调用该方法
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没有执行,调用postResult()
private void postResultIfNotInvoked(Result result) {
//用来判断mWorker是否调用了
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
//如果任务取消了,线程会中断,可能没有标识已经执行了(也就是没有设置为true),此处用来处理该中情况
postResult(result);
}
}
//给Handler发送消息,可以看出onPostExecute()是在UI线程中执行的
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
//获取标识
public final Status getStatus() {
return mStatus;
}
//在子线程中执行耗时操作,必须重写
@WorkerThread
protected abstract Result doInBackground(Params... params);
//在execute()中会看出是在主线程中执行的,并且最先调用,需要重写
@MainThread
protected void onPreExecute() {
}
//在Handler中调用,说明是在UI线程中执行的,需要重写
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onPostExecute(Result result) {
}
//在Handler中调用,是UI线程,需要重写
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onProgressUpdate(Progress... values) {
}
//如果任务取消的话,会在finish()中调用该方法
@SuppressWarnings({"UnusedParameters"})
@MainThread
protected void onCancelled(Result result) {
onCancelled();
}
//如果任务取消的话,会在finish()中调用该方法
@MainThread
protected void onCancelled() {
}
//标识是否取消任务
public final boolean isCancelled() {
return mCancelled.get();
}
//设置任务是否取消
public final boolean cancel(boolean mayInterruptIfRunning) {
//更新标识
mCancelled.set(true);
//中断任务,这里可以看出使用Future可好处:可以对子线程进行控制
return mFuture.cancel(mayInterruptIfRunning);
}
//获取任务执行的结果
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
//AsyncTask就是用此方法传递参数的
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
//execute正真执行的地方
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
//状态不是“挂起”,就报错,也就说明AsyncTask只能执行一次
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(),注意,此处仍然为UI线程
onPreExecute();
//传递相应的参数
mWorker.mParams = params;
//mFuture和mWorker配合,先后执行了doInBackground()和onPostExecute()
exec.execute(mFuture);
//进一步说明:此处使用了“模板模式”,在使用过程中,我们只要根据需求,重写onPreExecute(),doInBackground() ,onPostExecute()即可
return this;
}
//用线程池来执行Runnable,嗯,我想了半天,也就是可以省略一些配置,少些一些代码而已,没啥用
@MainThread
public static void execute(Runnable runnable) {
sDefaultExecutor.execute(runnable);
}
//在doInBackground()中使用,用来通知子线程的进度
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
//任务结束时,通过Handler来调用
private void finish(Result result) {
//根据是否取消来执行相应的方法
if (isCancelled()) {
onCancelled(result);
} else {
//根据需求,重写方法
onPostExecute(result);
}
//更新状态
mStatus = Status.FINISHED;
}
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;
}
}
}
//用来封装任务(子线程)数据
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
//用来封装Handler的数据
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
后记
AsyncTask中的成员变量大多是静态的,如果在一个地方替换掉的话,再次使用的时候需要清除,AsyncTask中的一些设置已经不是默认的。
转载请标明出处:http://blog.csdn.net/qq_26411333/article/details/51404760