Internal Implementation of Java AsyncTask Analysis
Before sdk3.0, the internal thread pool was used for multi-thread concurrent execution. The thread pool size is equal to 5 and the maximum size is 128.
After sdk3.0, use the default serial thread pool to execute a thread and then execute the next thread in sequence. When sdk4.3 is used, the thread pool size equals 5, and the maximum size is 128.
After sdk4.4, the thread pool size equals to cpu count + 1, and the maximum value is cpu count * 2 + 1
Sdk3.0 has two thread pools. The default is the Serial thread pool.
Public static final Executor SERIAL_EXECUTOR = new SerialExecutor (); public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor (CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit. SECONDS, sPoolWorkQueue, sThreadFactory); private static volatile Executor = SERIAL_EXECUTOR; public static void setDefaultExecutor (Executor exec) {// sets the default thread pool sDefaultExecutor = exec ;}
SerialExecutor, which uses a synchronization lock to execute one thread at a time
private static class SerialExecutor implements Executor { final ArrayDeque
mTasks = new ArrayDeque
(); 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); } } }
THREAD_POOL_EXECUTOR concurrent Thread Pool
Asynctask. setDefaultExecutor (AsyncTask. THREAD_POOL_EXECUTOR); // sets the concurrent thread pool.
Asynctask.exe cuteOnExecutor (executor); // you can customize the thread pool to use these two methods.