在類的定義說明中有這樣一句話
大概意思是你只能使用AsyncTask執(zhí)行一些運行周期短的操作(最多只有幾秒)如果是長周期的方法嚷炉,最好使用Executor崩侠,ThreadPoolExecutor 等娘赴。
AsyncTasks should ideally be
* used for short operations (a few seconds at the most.) If you need to keep threads
* running for long periods of time, it is highly recommended you use the various APIs
* provided by the <code>java.util.concurrent</code> package such as {@link Executor},
* {@link ThreadPoolExecutor} and {@link FutureTask}
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
AsyncTask 執(zhí)行execute的時候采用的是 sDefaultExecutor 作為executor荆几,sDefaultExecutor默認(rèn)的指向
/**
* 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();
...
...
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
下面來看一下SerialExecutor 的定義
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);
}
}
}
這里很有意思姑蓝,在SerialExecutor scheduleNext的方法里調(diào)用了 THREAD_POOL_EXECUTOR 的execute(mActive)
mActive 實際上是
new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
}
也就是AsyncTask通過 SerialExecutor 調(diào)度寞焙,使用 mTasks緩存乙漓,但是執(zhí)行的時候级历,采用的是THREAD_POOL_EXECUTOR,大家不難看出叭披,需要線程執(zhí)行完畢的時候寥殖,才會在finally里走進(jìn)scheduleNext(),繼續(xù)執(zhí)行涩蜘。
在這里要說一下嚼贡,如果沒用過AsyncTask 的同學(xué),可能沒辦法理解這個mTasks什么情況下會有緩存同诫,會有多個值粤策,大家可能注意到了 execute(Params... params),然后并不是這里误窖。這個地方的參數(shù)params在后面會講到叮盘,他是作為一個數(shù)組傳遞給了doInBackground方法。
那么這里是在什么情況下會有緩存數(shù)據(jù)呢霹俺?看下面定義
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
//大家看定義柔吼,這是一個靜態(tài)的Executor也就是說進(jìn)程中所有的AsyncTask都是通過同一個sDefaultExecutor 來調(diào)度的。
說到這里丙唧,大家可能明白了開篇說的那句話愈魏,如果執(zhí)行時間比較長,那么AsyncTask的sDefaultExecutor就會被卡住,后面的任務(wù)都無法執(zhí)行了蝌戒。
在類的構(gòu)造方法里,初始化了兩個變量串塑,其中一個是mWorker,他是一個Callable北苟,他的call方法桩匪,執(zhí)行了 result = doInBackground(mParams);并且最終調(diào)用了 postResult(result);通知用戶。
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
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
}
};
好了友鼻,就這樣傻昙,先說到這里,大家感興趣不防測試驗證一下彩扔。