private static final String LOG_TAG = "AsyncTask";
//获取cpu核心数
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
//核心线程数大部分情况为4
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
//最大核心线程数为cpu核心数*2+1
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());
}
};
//阻塞队列初始容量为128
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
//创建线程池对象
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;
}
/**
* 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();
//handler的消息用于发送更新进度的消息,和返回结果的消息
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
//这里将默认的线程池指定为串行的
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
private static InternalHandler sHandler;
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
//线程状态
private volatile Status mStatus = Status.PENDING;
//原子性的boolean对象
private final AtomicBoolean mCancelled = new AtomicBoolean();
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
//用于更新的handler
private final Handler mHandler;
//顺序执行的线程对象
private static class SerialExecutor implements Executor {
//队列维护的任务
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
//当前执行的任务
Runnable mActive;
//执行方法
public synchronized void execute(final Runnable r) {
//offer方法是创建一个Ruannable放进mTask队列里面
mTasks.offer(new Runnable() {
public void run() {
try {
//这里r是我们正真要执行的任务,如果不调用run方法,是不会执行的
r.run();
} finally {
//执行下一个任务
scheduleNext();
}
}
});
//如果当前执行的任务为空,则执行队列里面的下一个任务
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
//Task调用该pop方法将队列的第一个任务弹出并赋值给mActive对象
if ((mActive = mTasks.poll()) != null) {
//执行mActive任务
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
//代表当前任务状态,比如有3个任务,属于线程私有
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 getMainHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler(Looper.getMainLooper());
}
return sHandler;
}
}
//AsyncTask对象的初始化,当未传递参数时 会调用 step3处的方法
public AsyncTask() {
this((Looper) null);
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Handler handler) {
this(handler != null ? handler.getLooper() : null);
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
//step3
public AsyncTask(@Nullable Looper callbackLooper) {
//假设我们没有传入looper对象 就会把上面的初始化的handler对象作为mHand'er的值
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
//WorkerRunnable 实现了 CallAble接口 callable 接口解释如下:Callable 接口类似于 //Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是 Runnable
//不会返回结果,并且无法抛出经过检查的异常。
//意思就是说这个在线程里面执行了会返回一个结果给调用的位置
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
//doInBackground为抽象方法由自己重写逻辑,比如下载,或者io等
//在我们把需要执行的任务执行完后会返回这个结果
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
//将结果通过handler发送到主线程,
postResult(result);
}
return result;
}
};
//在程序走到这里其实上面的worker是没有执行的只是相当于创建了一个任务
//将这个任务交给FutureTask来执行
//jdk API 1.6 解释如下
/**可取消的异步计算。利用开始和取消计算的方法、查询计算是否完成的方法和获取计算结果的方法,此类提供了对 Future 的基本实现。仅在计算完成时才能获取结果;如果计算尚未完成,则阻塞 get 方法。一旦计算完成,就不能再重新开始或取消计算。
可使用 FutureTask 包装 Callable 或 Runnable 对象。因为 FutureTask 实现了 Runnable,所以可将 FutureTask 提交给 Executor 执行。
除了作为一个独立的类外,此类还提供了 protected 功能,这在创建自定义任务类时可能很有用。 */
//上面描述很清楚,可以获取计算结果,可以取消,
/**FutureTask实现了Runnable接口,所以在下面AsyncTask里面执行execute方法时
会调用这个方法
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
上面的方法会调用下面的方法,而exec 就是默认的sDefaultExecutor,这个串行的线程池调用
execute(mFuture)方法时,mFuture在创建Async对象时已经赋值了.又回到SerialExecute的execute方法,将这个mFuture添加到ArrayDeque队列进行执行.
@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;
}
*/
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);
}
}
};
}
//第一次写上面逻辑有点乱,下面按顺寻整理
//step1. 创建AsyncTask对象 这里创建了一个Future对象,就是个Runnable,
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
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
//step8.子线程执行的结果在这里返回
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
//step9.将执行的结果发送到handler处理
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);
}
}
};
}
//step2.调用execute方法
public static void execute(Runnable runnable) {
sDefaultExecutor.execute(runnable);
}
//step3.调用SerialExecute里面的方法 传入的mFuture添加到ArrayDeque里面去
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
//这里还是在主线程,这里的execute只是添加了一个任务
public synchronized void execute(final Runnable r) {
//step4.这里只是创建了一个Runnable对象将其添加到队列,但是并未运行,所以r.run()没有运行
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
//setp7.这里一定循环的点,继续执行下一个任务
scheduleNext();
}
}
});
if (mActive == null) {
//step5.这个mActive是空
scheduleNext();
}
}
protected synchronized void scheduleNext() {
//step6.将刚刚创建的任务弹出队列,执行 就会执行到r.run()方法,执行完后进入finally
if ((mActive = mTasks.poll()) != null) {
//线程池执行的点在这里
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
//step11.发送消息
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 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:
// There is only one result
//step13.这里更新已经将结果发送到主线程了,
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
//step14.Async的finish方法 onPostExecute这里又我们复写,接收处理结果
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
/**
总结: 核心是AsyncTask初始化创建的mFuture对象,以及是SerialExecute将任务添加到队列的方法
和最后将任务发给线程池执行,最终在mWorker对象里面将结果返回后将结果通过handler发送,再交由handleMessage去处理结果
*/