//AsyncTask是個(gè)抽象類
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
//Cpu數(shù)量胡陪,創(chuàng)建線程池使用
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//核心線程合陵,創(chuàng)建線程池使用
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
//最大線程數(shù)量,創(chuàng)建線程池使用
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
//存活時(shí)間聚请,創(chuàng)建線程池使用
private static final int KEEP_ALIVE = 1;
//創(chuàng)建線程的工廠sThreadFactory伞广,創(chuàng)建線程池使用
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任務(wù)的隊(duì)列堰塌,創(chuàng)建線程池使用
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
//創(chuàng)建線程池THREAD_POOL_EXECUTOR, 實(shí)現(xiàn)多線程并行
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種類:發(fā)送結(jié)果
private static final int MESSAGE_POST_RESULT = 0x1;
//Message種類:發(fā)送進(jìn)度
private static final int MESSAGE_POST_PROGRESS = 0x2;
//默認(rèn)的線程池:串行的線程池
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
//內(nèi)部的Handler
private static InternalHandler sHandler;
//WorkerRunnable是自定義的Callable,從參數(shù)猜測是用來存放傳進(jìn)來的參數(shù)和傳出去的結(jié)果
private final WorkerRunnable<Params, Result> mWorker;
//FutureTask是繼承至RunableFuture琼牧,可接收一個(gè)callable為參數(shù)恢筝,可以有返回結(jié)果,而且里面cancel(boolean mayInterruptIfRunning)可以取消任務(wù)
private final FutureTask<Result> mFuture;
//事件狀態(tài)
private volatile Status mStatus = Status.PENDING;
//是否取消任務(wù)
private final AtomicBoolean mCancelled = new AtomicBoolean();
//標(biāo)識任務(wù)是否被執(zhí)行過
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
//串行的線程池巨坊,保證串行順序執(zhí)行任務(wù)
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {//將 Runnable加入到隊(duì)列中撬槽,再THREAD_POOL_EXECUTOR處理Runnable
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {//上面執(zhí)行完畢后才能執(zhí)行下一個(gè)任務(wù)
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.
* 每一種狀態(tài)只能改變一次,也就是說整個(gè)生命周期只能執(zhí)行一次任務(wù)
*/
public enum Status {
/**
* Indicates that the task has not been executed yet.
*/
PENDING,//待定狀態(tài)
/**
* Indicates that the task is running.
*/
RUNNING,//執(zhí)行狀態(tài)
/**
* Indicates that {@link AsyncTask#onPostExecute} has finished.
*/
FINISHED,//結(jié)束狀態(tài)
}
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();//這里直接new Handler(),說明是在UI線程中進(jìn)行的趾撵,所以AsyncTask要在主線程初始化
}
return sHandler;
}
}
/** @hide */
public static void setDefaultExecutor(Executor exec) {//設(shè)置默認(rèn)線程池侄柔,可選串行和并行
sDefaultExecutor = exec;
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
//mWork是繼承自callable,封裝成執(zhí)行doInBackground的單位
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);//任務(wù)被執(zhí)行了
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);//設(shè)置線程優(yōu)先級是后臺線程
//noinspection unchecked
Result result = doInBackground(mParams);//執(zhí)行doInBackground(),并保存結(jié)果
Binder.flushPendingCommands();
return postResult(result);//將結(jié)果發(fā)送出去
}
};
//FutureTask使用Callable作為構(gòu)造函數(shù)的參數(shù)
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());//返回結(jié)果: 如果mTaskInvoked==true占调,則不會返回結(jié)果暂题,因?yàn)樵趍Worker里面已經(jīng)返回了
} 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);//取消執(zhí)行
}
}
};
}
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();//檢查是否執(zhí)行過
if (!wasTaskInvoked) {//未執(zhí)行過
postResult(result);
}
}
private Result postResult(Result result) {//將結(jié)果封裝在Message,發(fā)送給Handler處理
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));//將結(jié)果給內(nèi)部Handler處理
message.sendToTarget();
return result;
}
/**
* Returns the current status of this task.
*
* @return The current status.
* 獲取目前狀態(tài)
*/
public final Status getStatus() {
return mStatus;
}
@WorkerThread //執(zhí)行的方法究珊,在線程池處理
protected abstract Result doInBackground(Params... params);
@MainThread //執(zhí)行前調(diào)用薪者,在UI線程執(zhí)行
protected void onPreExecute() {
}
@SuppressWarnings({"UnusedDeclaration"})
@MainThread //執(zhí)行后調(diào)用,在UI線程執(zhí)行
protected void onPostExecute(Result result) {
}
@SuppressWarnings({"UnusedDeclaration"})
@MainThread //進(jìn)度改變剿涮,在UI線程執(zhí)行
protected void onProgressUpdate(Progress... values) {
}
@SuppressWarnings({"UnusedParameters"})
// //執(zhí)行取消后調(diào)用的方法
@MainThread
protected void onCancelled(Result result) {
onCancelled();
}
//執(zhí)行取消后調(diào)用的方法
@MainThread
protected void onCancelled() {
}
/**
* 檢查任務(wù)是否取消
*/
public final boolean isCancelled() {
return mCancelled.get();
}
/**
* 取消任務(wù)
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
mCancelled.set(true);
return mFuture.cancel(mayInterruptIfRunning);
//取消mFuture任務(wù)言津,不需要發(fā)送信息給handler,因?yàn)閙Future結(jié)束后取试,也會發(fā)送postResult給Handler悬槽,
//Handler就可以根據(jù)mCancelled進(jìn)行處理
}
/**
* 獲取任務(wù)執(zhí)行的結(jié)果
*/
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
/**
* 最多等待為使計(jì)算完成所給定的時(shí)間之后,檢索其結(jié)果(如果結(jié)果可用),則返回
*/
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return mFuture.get(timeout, unit);
}
/**
* execute調(diào)用executeOnExecutor
*/
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);//使用默認(rèn)的線程池
}
/**
* 分析的入口
*/
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
//檢查狀態(tài)
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)");
}
}
//將狀態(tài)設(shè)置為運(yùn)行,在workRunnable執(zhí)行的時(shí)候也會設(shè)置為running狀態(tài)
mStatus = Status.RUNNING;
//可見onPreExecute是在主線程進(jìn)行
onPreExecute();
//將參數(shù)也賦進(jìn)去
mWorker.mParams = params;
//加入線程池執(zhí)行
exec.execute(mFuture);
return this;
}
//如果參數(shù)是runnable瞬浓,直接通過默認(rèn)的線程池執(zhí)行初婆,跟普通線程池運(yùn)行差不多
@MainThread
public static void execute(Runnable runnable) {
sDefaultExecutor.execute(runnable);
}
/**
* 改變進(jìn)度,可以在doInbackground調(diào)用
*/
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
//任務(wù)結(jié)束,這個(gè)方法是在Handler里面調(diào)用
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);//執(zhí)行取消
} else {
onPostExecute(result);//任務(wù)完成
}
mStatus = Status.FINISHED;
}
//內(nèi)部定義的Handler
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());//獲取Looper
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {//對AsyncTaskResult進(jìn)行處理
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT://任務(wù)結(jié)束
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS://改變進(jìn)度
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
//自定義的帶有參數(shù)的Callable
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
//封裝的返回結(jié)果磅叛,主要給handler使用的
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
總結(jié): 好累屑咳,下次再總結(jié)吧...