SerialExecutor解析
阅读郭霖大神博客笔记
博客地址: http://blog.csdn.net/guolin_blog/article/details/11711405
SerialExecutor是AsyncTask在3.0版本以后做了最主要的修改的地方,
它在AsyncTask中是以常量的形式被使用的,
所以在整个应用程序中的所有AsyncTask实例都会共用同一个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使用ArrayDeque这个队列来管理Runnable对象,
第一次运行execute的时候,
会调用ArrayDeque的offer方法将传入的Runnable对象添加到队列的尾部.
然后判断mActive是否为空,
如果为空,那么就调用scheduleNext()方法.
在这个方法里面会从队列的头部取值,赋值给mActive对象,
然后调用THREAD_POOL_EXECUTOR去执行取出的取出的Runnable对象
Android 3.0之前没有SerialExecutor这个类,
那个时候是直接在AsyncTask中构建了一个sExecutor常量,
并对线程池总大小,同一时刻能够运行的线程数做了规定.
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final int KEEP_ALIVE = 10;
……
private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);