android系統(tǒng)對于UI線程的刷新維持在16ms左右,如果在主線程進行一些操作,我們需要限制時間,以保證用戶不會在操作過程中覺得卡頓,那么一些耗時操作最好不要在主線程中進行,如果強行操作可能存在各種問題,所以需要我們?nèi)ピ谧泳€程中去實現(xiàn)耗時操作,然后去通知主線程去更新UI,之前一篇文章寫過 ,可以創(chuàng)建線程,或者創(chuàng)建線程池來實現(xiàn)這方面的功能。
在jdk1.5的時候,推出了一個AsyncTask的類,這個類有效的幫助我們實現(xiàn)上面要求的功能,他比較適用于一些耗時比較短的任務(wù),內(nèi)部封裝了線程池,實現(xiàn)原理是FutureTask+Callable +SerialExecutor (線程池)。
先說整個流程,在AsyncTask的構(gòu)造方法中 ,會創(chuàng)建Future對象跟Callable對象,然后在execute方法中會執(zhí)行onPreExecute()方法跟doInBackground方法,而doInbackground 的結(jié)果,會被封裝成一個Message,再通過handler來進行線程間通信,通過這個message.what來識別 是否需要調(diào)用onProgressUpdate,或是finish方法 。finish方法里面會調(diào)用onPostExecute方法 。
另外我們可以通過publishProgress()方法來主動調(diào)用onProgressUpdate()方法,內(nèi)部也是通過這個方法,來發(fā)出一個這樣的message去調(diào)用onProgressUpdate的。
上代碼:
class MyAsyncTask extends AsyncTask<Void, Integer, Boolean> {
//第一個參數(shù)Params :外界傳進來,任務(wù)所需的參數(shù) 是doInBackground的參數(shù)
//第二個參數(shù)Progress: onProgressUpdate的參數(shù),一般用于展示任務(wù)進度
//第三個參數(shù)Result :當(dāng)doInBackground執(zhí)行完 返回的參數(shù) ,是onPostExecute的參數(shù)
@Override
protected void onPreExecute() {
super.onPreExecute();
//可以在這里進行 執(zhí)行任務(wù)之前的準(zhǔn)備
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
//可以在這個方法中進行進度的展示 這個方法是在UI線程的
}
@Override
protected Boolean doInBackground(Void... params) {
//在這里執(zhí)行任務(wù) 是在子線程中執(zhí)行
return null;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
//當(dāng)任務(wù)執(zhí)行完畢后 調(diào)用這個方法 可以在這里進行UI的更新 這個方法也是在UI線程的
}
}
用的時候很簡單,在上述一些方法中去寫需求,然后直接調(diào)用:
new MyAsyncTask().execute();//最好弱引用+靜態(tài)內(nèi)部類哦 不然有可能內(nèi)存泄漏的
現(xiàn)在開始分析源碼(基于android7.0),首先看AsyncTask的構(gòu)造函數(shù):
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
* 創(chuàng)建一個異步任務(wù) 構(gòu)造函數(shù)必定執(zhí)行在ui線程
*/
public AsyncTask() {
//創(chuàng)建一個Callable對象
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);
Binder.flushPendingCommands();
return postResult(result);
}
};
//創(chuàng)建一個FuntureTask對象 并且把上面的Callable對象當(dāng)做參數(shù)傳進去
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);
}
}
};
}
執(zhí)行execute方法:
//執(zhí)行execute代碼:
//This method must be invoked on the UI thread.
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);//簡單調(diào)用這個方法
}
//觀察這個方法的第一個參數(shù),是個常量
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;//靜態(tài)的 屬于類
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
//有個關(guān)鍵點需要注意的是 所有的AsyncTask 都共用一個SerialExecutor
再看executeOnExecutor方法:
@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;//狀態(tài)變更為正在執(zhí)行
onPreExecute(); //觀察到 onPreExecute方法首先被執(zhí)行 并且在UI線程中執(zhí)行
mWorker.mParams = params;
//這個exec 就是SerialExecutor
exec.execute(mFuture);//通過這個線程池 去執(zhí)行這個futureTask
return this;
}
再看這個execute 會如何調(diào)用
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); //維持一個ArrayDeque,將所有的任務(wù) 放置在里面
Runnable mActive;//當(dāng)前任務(wù)
//這個Runnable對象 即初始化時候創(chuàng)建的mFuture對象
public synchronized void execute(final Runnable r) {
//這個offer方法,即把當(dāng)前的任務(wù) 加入到上面的隊列尾部
mTasks.offer(new Runnable() {
public void run() {
//子線程中進行
try {
r.run();//這個方法會執(zhí)行mFuture里面的mWorker
//這里會執(zhí)行call方法里面的 doInBackground方法
} finally {
scheduleNext();
}
}
});
//這里開始執(zhí)行 第一次必定為null 隨后執(zhí)行scheduleNext方法
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
//他會從隊列當(dāng)中 再次拿一個任務(wù) 賦給mActive,進行執(zhí)行
if ((mActive = mTasks.poll()) != null) {
//通過這個ThreadPoolExecute去執(zhí)行這個任務(wù) 就這樣 一個一個拿出來執(zhí)行
//從形式上來說 可以認(rèn)為是單線程池執(zhí)行任務(wù),以此解決并發(fā)的問題
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
以上,我們就重新執(zhí)行到了mWorker里面的call方法了,可以看出 ,這個call方法是在子線程中執(zhí)行的,我們再看postResult方法:
private Result postResult(Result result) {
//將這個result 拼成一個Message對象 ,通過handler發(fā)送出去
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();//發(fā)送message 執(zhí)行任務(wù)
return result;
}
//獲取handler
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
//就一個普通的靜態(tài)內(nèi)部類 繼承Handler
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://執(zhí)行這塊分支
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS: //這里 需要調(diào)用publishProgress() 就會發(fā)送這種message
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
最后看這個finish方法:
private void finish(Result result) {
if (isCancelled()) {//如果為true 表示要取消任務(wù)
onCancelled(result);
} else {//否則執(zhí)行這塊分支
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
之后再看一下如何執(zhí)行到handler里面的MESSAGE_POST_PROGRESS分支好了:
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
//這樣 就會進入MESSAGE_POST_PROGRESS分支,執(zhí)行onProgressUpdate方法了。
}
}
整個流程已經(jīng)順利走通了,最后我們再看一下,如何取消當(dāng)前正在執(zhí)行的任務(wù)。
execute.cancel(true);//單純這么調(diào)用下就可以了
//當(dāng)前參數(shù)意味著 是否允許任務(wù)執(zhí)行完畢 ,如果false 則是允許執(zhí)行完畢,否則直接中斷
//看源碼注釋 知道中斷任務(wù)可能會失敗 因為任務(wù)可能已經(jīng)執(zhí)行完畢了
public final boolean cancel(boolean mayInterruptIfRunning) {
mCancelled.set(true);//設(shè)置為true,會將里面的一個變量value設(shè)置為1
return mFuture.cancel(mayInterruptIfRunning);//中斷future里面的callable的執(zhí)行
}
//設(shè)置value成1之后 上面的finish方法 就會進入onCancelled()分支 ,這里面什么都沒有操作
總結(jié):
在整個應(yīng)用程序中的所有AsyncTask實例都會共用同一個SerialExecutor,他是用一個ArrayDueue來管理所有的Runnable的,那么所有的任務(wù) 就會都在一個隊列當(dāng)中了,他在execute方法中,會通過scheduleNext,一個一個的從隊列中取出頭部任務(wù),進行執(zhí)行,而后面添加的任務(wù),都是放在隊列的尾部。
總體來看 ,這個SerialExecutor ,功能上講屬于單一線程池,如果我們快速地啟動了很多任務(wù),同一時刻只會有一個線程正在執(zhí)行,其余的均處于等待狀態(tài)。
在4.0以前的版本 ,是直接使用ThreadPoolExecutor的,核心線程數(shù)為5,總線程數(shù)為128的線程池。
現(xiàn)在的AsyncTask已經(jīng)可以自定義線程池,來進行相應(yīng)的操作了,靈活性比較高。
總而言之,AsyncTask也是使用的異步消息處理機制,只是做了非常好的封裝而已。