Android AsyncTask 分析内部实现

时人不识凌云木,直待凌云始道高。这篇文章主要讲述Android AsyncTask 分析内部实现相关的知识,希望能为你提供帮助。
转载自:http://blog.csdn.net/jjwwmlp456/article/details/38623563
 
 
sdk3.0前,使用内部的线程池,多线程并发执行。线程池大小等于5,最大达128
sdk3.0后,使用默认的serial线程池,执行完一个线程,再顺序执行下一个线程。sdk3.0< =current version < = sdk4.3时  线程池大小等于5,最大达128
sdk4.4后线程池大小等于 cpu count + 1,最大值为cpu count * 2 + 1
sdk3.0后有两种线程池的实现,默认为 Serial 线程池
 

1 public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); 2 public static final Executor THREAD_POOL_EXECUTOR 3= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, 4TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); 5 private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; 6 public static void setDefaultExecutor(Executor exec) {//设置默认线程池 7sDefaultExecutor = exec; 8 }

 
【Android AsyncTask 分析内部实现】SerialExecutor  ,使用同步锁,一次执行一个线程
 
 
1 private static class SerialExecutor implements Executor { 2final ArrayDeque< Runnable> mTasks = new ArrayDeque< Runnable> (); 3Runnable mActive; 4 5public synchronized void execute(final Runnable r) { 6mTasks.offer(new Runnable() { 7public void run() { 8try { 9r.run(); 10} finally { 11scheduleNext(); 12} 13} 14}); 15if (mActive == null) { 16scheduleNext(); 17} 18 } 19 20protected synchronized void scheduleNext() { 21if ((mActive = mTasks.poll()) != null) { 22THREAD_POOL_EXECUTOR.execute(mActive); 23} 24} 25}

THREAD_POOL_EXECUTOR 并发线程池
 
asynctask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR); //设置使用 并发线程池 
//params 都是使用在doInBackground(Params... params);
asynctask.executeOnExecutor(executor, params); //可以自定义 线程池     使用这两种方法

    推荐阅读