前言
好久沒看過源碼了,前幾天面試被問到一臉懵逼昧绣,全忘掉了。復(fù)習(xí)一下捶闸,做個(gè)筆記分享夜畴。AsyncTask是android開發(fā)中一個(gè)非常重要的異步類,可以在異步線程中做一些耗時(shí)的操作删壮。本文參照源碼對AsyncTask進(jìn)行簡單的解析贪绘。
一、AsyncTask簡介及基本使用央碟。
1税灌、AsyncTask簡介
??AsyncTask是對針對Handler+線程池的封裝,可以在異步的去更新UI亿虽,使用方式簡單便捷菱涤,僅需要繼承AsyncTask抽象類,并實(shí)現(xiàn)幾個(gè)基本方法即可洛勉,需要注意的是必須要在UI線程進(jìn)行調(diào)用粘秆,因?yàn)锳syncTask使用的Handler為UI線程 下的Handler,只有這樣才可以在子線程去更新UI線程坯认。
??AsyncTask類的聲明如下:
public abstract class AsyncTask<Params, Progress, Result>
其中:
?Params為傳入到doInBackground方法的參數(shù)類型翻擒;
?Progress為進(jìn)度條所使用的參數(shù)類型氓涣;
?Result為線程完成后返回值的參數(shù)類型牛哺;
AsyncTask主要的方法有五個(gè):
onPreExecute() : 在線程池開始進(jìn)行任務(wù)之前調(diào)用,為準(zhǔn)備工作
doInBackground(Params… params) :線程中進(jìn)行的工作劳吠,唯一一個(gè)在子線程運(yùn)行的方法
onProgressUpdate(Progress… values):顯示線程中工作進(jìn)度引润,調(diào)用方法在doInBackground中的
publishProgress方法
onPostExecute(Result result) :線程結(jié)束后會(huì)通過handler調(diào)用到onPostExecute方法,并返回結(jié)果
cancel(boolean mayInterruptIfRunning):中途打斷線程運(yùn)行痒玩,但不一定會(huì)成功淳附。如果任務(wù)已經(jīng)完成,
則無論mayInterruptIfRunning為true還是false蠢古,此方法肯定返回false奴曙,即如果取消已經(jīng)完成的任務(wù)會(huì)
返回false;如果任務(wù)正在執(zhí)行草讶,若mayInterruptIfRunning設(shè)置為true洽糟,則返回true,若mayInterruptI
fRunning設(shè)置為false,則返回false坤溃;如果任務(wù)還沒有執(zhí)行拍霜,則無論mayInterruptIfRunning為true還是
false,肯定返回true薪介。
2祠饺、AsyncTask注意事項(xiàng)
1、AsyncTask并不會(huì)隨Activiy關(guān)閉而取消汁政,doInbackground依然會(huì)運(yùn)行道偷,直到線程結(jié)束后會(huì)調(diào)用finish()方法,如果在關(guān)閉前調(diào)用過cancel()方法记劈,會(huì)調(diào)onCancelled()方法试疙,如果沒有的話,會(huì)直接跳轉(zhuǎn)OnPostExecute()方法抠蚣,可能會(huì)導(dǎo)致AsyncTask報(bào)錯(cuò)崩潰祝旷。
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
2、如果屏幕旋轉(zhuǎn)或其他方式導(dǎo)致Activity重新創(chuàng)建嘶窄,那么AsyncTask所持有的Activity中的引用會(huì)失效怀跛,OnPostExecute()方法繪制的時(shí)候?qū)⒉粫?huì)有效果。
3柄冲、要注意并行和串行吻谋,分別由execute()和executeOnExecutor(Executor)控制。
3现横、源碼分析
AsyncTask構(gòu)造器:
public AsyncTask() {
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);
}
};
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);
}
}
};
}
很明顯漓拾,在構(gòu)造器中new了兩個(gè)對象,分別為WorkerRunnable和FutureTask(FutrueTask為java并發(fā)編程中一個(gè)比較重要類戒祠,如果不了解的話骇两,請百度一下,或者看我下一篇文章)姜盈。doInBackground()方法在mWorker的call()方法中被調(diào)用低千,且返回值在postResult()方法中被調(diào)用。
我們來看一下WorkerRunnable類的源碼和FutureTask的構(gòu)造方法馏颂。
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
很明顯示血,WorkerRunnable類實(shí)現(xiàn)了Callable的接口。被FutureTask作為參數(shù)傳入救拉。這就說明doInbackground()實(shí)際是在異步線程中被調(diào)用难审。且實(shí)際上AsyncTask的成員mWorker包含了AyncTask要執(zhí)行的任務(wù)。那么mWorker的call()方法到底什么時(shí)候會(huì)被調(diào)用呢亿絮,了解過FutureTask運(yùn)行機(jī)制的朋友都知道FutureTask只有被放到線程池中的時(shí)候才會(huì)被調(diào)用告喊,進(jìn)而調(diào)用到call()方法拂铡。
在看一下剛剛注意事項(xiàng)里說道的execute()方法的源碼:
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
由源碼可以,該方法僅能在主線程中使用葱绒,另外execute返回的是executeOnExecutor方法的返回值感帅,參數(shù)為sDefaultExecutor和params。
首先來看下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;
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
第一個(gè)參數(shù)為線程調(diào)度的對象地淀,第二個(gè)參數(shù)為mWorker的mParams參數(shù)失球,由上面的源碼可知,mParams參數(shù)是傳到doInBackground中的帮毁。另外executeOnExecutor()方法中還調(diào)用了onPreExecute()实苞,之后才會(huì)調(diào)用exec.execute(mFuture);說明onPreExecute方法的確是在主線程中調(diào)用,且在子線程開始之前調(diào)用烈疚。
我們再看看sDefaultExecutor參數(shù):
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
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) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
很簡單黔牵,sDefaultExecutor 為SerialExecutor類 的一個(gè)對象,且標(biāo)識(shí)為volatile爷肝,以防止線程問題猾浦。SerialExecutor 的實(shí)現(xiàn)中可以看到,線程池維持了一個(gè)Runnable的隊(duì)列灯抛。mActive為正在運(yùn)行的線程金赦,當(dāng)調(diào)用execute()方法時(shí)在隊(duì)列末尾插入需要運(yùn)行的Runnable對象。并調(diào)用scheduleNext();方法对嚼。如果當(dāng)前運(yùn)行的Runnable對象為空的話夹抗,會(huì)繼續(xù)調(diào)用scheduleNext(),在scheduleNext()方法中可以看到首先mTasks出隊(duì)給mActive賦值纵竖,如果不為空漠烧,則
??THREAD_POOL_EXECUTOR.execute(mActive)
我們來看一下THREAD_POOL_EXECUTOR是什么
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
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;
}
可以看出來THREAD_POOL_EXECUTOR是一個(gè)線程池對象,為真正開始異步邏輯的載體靡砌。
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
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE_SECONDS = 30;
由注釋可以看出已脓,編寫者希望線程池基本大小(CORE_POOL_SIZE )最少為2個(gè)線程,最多為4個(gè)線程乏奥,來維持線程池的運(yùn)轉(zhuǎn)摆舟,只有在隊(duì)列滿的時(shí)候才會(huì)創(chuàng)建更多的線程。線程池中允許的最大線程數(shù)(MAXIMUM_POOL_SIZE )為CPU的數(shù)目的2倍+1,線程空閑時(shí)超時(shí)時(shí)間(KEEP_ALIVE_SECONDS )為30s邓了。
另外在上面說過當(dāng)WorkerRunnable任務(wù)做完的時(shí)候會(huì)調(diào)用postResult()方法∠钡桑看一下源碼
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
當(dāng)任務(wù)做完的時(shí)候會(huì)發(fā)送message到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:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
如果為MESSAGE_POST_RESULT骗炉,則會(huì)調(diào)用finish()方法,在上文中已經(jīng)說到過該方法蛇受,由構(gòu)造方法可以看出句葵,InternalHandler使用的為主線程的looper,故而可以在handleMessage中刷新UI。
另外還有一個(gè)publishProgress:
@WorkerThread
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
也是通過message通知handler刷新UI乍丈。
如果有什么問題歡迎留言或給我發(fā)郵件 tlioylc@gmail.com
良心干貨剂碴,歡迎關(guān)注