//AsyncTask是个抽象类
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;
//创建线程的工厂sThreadFactory,创建线程池使用
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());
}
};
//存放Runnable任务的队列,创建线程池使用
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
//创建线程池THREAD_POOL_EXECUTOR, 实现多线程并行
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
//自定义的串行线程池
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
//Message种类:发送结果
private static final int MESSAGE_POST_RESULT = 0x1;
//Message种类:发送进度
private static final int MESSAGE_POST_PROGRESS = 0x2;
//默认的线程池:串行的线程池
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
//内部的Handler
private static InternalHandler sHandler;
//WorkerRunnable是自定义的Callable,从参数猜测是用来存放传进来的参数和传出去的结果
private final WorkerRunnable<Params, Result> mWorker;
//FutureTask是继承至RunableFuture,可接收一个callable为参数,可以有返回结果,而且里面cancel(boolean mayInterruptIfRunning)可以取消任务
private final FutureTask<Result> mFuture;
//事件状态
private volatile Status mStatus = Status.PENDING;
//是否取消任务
private final AtomicBoolean mCancelled = new AtomicBoolean();
//标识任务是否被执行过
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
//串行的线程池,保证串行顺序执行任务
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {//将 Runnable加入到队列中,再THREAD_POOL_EXECUTOR处理Runnable
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);//使用THREAD_POOL_EXECUTOR处理Runnable
}
}
}
/**
* 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,//结束状态
}
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();//这里直接new Handler(),说明是在UI线程中进行的,所以AsyncTask要在主线程初始化
}
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() {
//mWork是继承自callable,封装成执行doInBackground的单位
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);//任务被执行了
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);//设置线程优先级是后台线程
//noinspection unchecked
Result result = doInBackground(mParams);//执行doInBackground(),并保存结果
Binder.flushPendingCommands();
return postResult(result);//将结果发送出去
}
};
//FutureTask使用Callable作为构造函数的参数
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());//返回结果: 如果mTaskInvoked==true,则不会返回结果,因为在mWorker里面已经返回了
} 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) {//未执行过
postResult(result);
}
}
private Result postResult(Result result) {//将结果封装在Message,发送给Handler处理
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));//将结果给内部Handler处理
message.sendToTarget();
return result;
}
/**
* Returns the current status of this task.
*
* @return The current status.
* 获取目前状态
*/
public final Status getStatus() {
return mStatus;
}
@WorkerThread //执行的方法,在线程池处理
protected abstract Result doInBackground(Params... params);
@MainThread //执行前调用,在UI线程执行
protected void onPreExecute() {
}
@SuppressWarnings({"UnusedDeclaration"})
@MainThread //执行后调用,在UI线程执行
protected void onPostExecute(Result result) {
}
@SuppressWarnings({"UnusedDeclaration"})
@MainThread //进度改变,在UI线程执行
protected void onProgressUpdate(Progress... values) {
}
@SuppressWarnings({"UnusedParameters"})
// //执行取消后调用的方法
@MainThread
protected void onCancelled(Result result) {
onCancelled();
}
//执行取消后调用的方法
@MainThread
protected void onCancelled() {
}
/**
* 检查任务是否取消
*/
public final boolean isCancelled() {
return mCancelled.get();
}
/**
* 取消任务
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
mCancelled.set(true);
return mFuture.cancel(mayInterruptIfRunning);
//取消mFuture任务,不需要发送信息给handler,因为mFuture结束后,也会发送postResult给Handler,
//Handler就可以根据mCancelled进行处理
}
/**
* 获取任务执行的结果
*/
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
/**
* 最多等待为使计算完成所给定的时间之后,检索其结果(如果结果可用),则返回
*/
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return mFuture.get(timeout, unit);
}
/**
* execute调用executeOnExecutor
*/
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);//使用默认的线程池
}
/**
* 分析的入口
*/
@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)");
}
}
//将状态设置为运行,在workRunnable执行的时候也会设置为running状态
mStatus = Status.RUNNING;
//可见onPreExecute是在主线程进行
onPreExecute();
//将参数也赋进去
mWorker.mParams = params;
//加入线程池执行
exec.execute(mFuture);
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;
}
//内部定义的Handler
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());//获取Looper
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {//对AsyncTaskResult进行处理
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;
}
}
}
//自定义的带有参数的Callable
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;
}
}
}
总结: 好累,下次再总结吧...