java.util.concurrent
pacakge
such as Executor
, ThreadPoolExecutor
and FutureTask
.- The AsyncTask class must be loaded on the UI thread. This is done automatically as of
JELLY_BEAN
. - AsyncTask類必須在UI線程被加載
- The task instance must be created on the UI thread.
- 類實例必須被在UI線程創建
execute(Params...)
must be invoked on the UI thread.- execute方法必須在UI線程被調用
- Do not call
onPreExecute()
,onPostExecute(Result)
,doInBackground(Params...)
,onProgressUpdate(Progress...)
manually. - 不要顯式調用這些方法
- The task can be executed only once (an exception will be thrown if a second execution is attempted.)
- 任務只能被執行一次,第二次被執行就會拋出異常。
DONUT
,
this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB
,
tasks are executed on a single thread to avoid common application errors caused by parallel execution.深入研究了下源碼,目前默認確實是單一後臺線程執行的,源碼如下:
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();//防備提交的其中某個runnale方法造成異常阻塞其他提交
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
從上面可以看出,雖然裏面用了線程池,但使用加鎖的機制,並且使用雙向隊列保證了串行提交(不一定是串行執行的,因爲線程池會在提交之後立刻返回,但是如果線程池滿,就要阻塞,這個機制的)。