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);
}
}
}
从上面可以看出,虽然里面用了线程池,但使用加锁的机制,并且使用双向队列保证了串行提交(不一定是串行执行的,因为线程池会在提交之后立刻返回,但是如果线程池满,就要阻塞,这个机制的)。