近期被多次问道:1.多个AsyncTask是并行还是串行;2.如何实现并行。平时没有在意这个问题,所以没有解释清楚,今天总结一下吧:
1.先说并行还是串行这个问题吧:从1.5引入的时候的确是串行的,在1.6-2.3.2的时候执行顺序更改为并行了,在3.0之后又改回了串行。问题到此为止吧!不要去介意这个了。
2.那么在平时使用中如何实现并行呢?
- 最直接的办法就是在new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXRCUTOR);
这样使用了AsyncTask默认的线程池,如果要自定义并行线程数,可以用第二个方法: - ExecutorService exec = Executors.newFixedThreadPool(int i); // i为自定义的线程数量。
然后使用new MyAsyncTask().executeOnExecutor(exec);
到此可以结束了,下面是一些与之相关的AsyncTask源码,看过的源码的人可以直接关闭了。
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
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;
private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128);
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
// 看这里,刚才用到的
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;
}