首页 > 代码库 > 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,  
4                     TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);  
5 private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;  
6 public static void setDefaultExecutor(Executor exec) {//设置默认线程池  
7         sDefaultExecutor = exec;  
8 }  

 

SerialExecutor ,使用同步锁,一次执行一个线程

 

 

 1 private static class SerialExecutor implements Executor {  
 2         final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();  
 3         Runnable mActive;  
 4   
 5         public synchronized void execute(final Runnable r) {  
 6             mTasks.offer(new Runnable() {  
 7                 public void run() {  
 8                     try {  
 9                         r.run();  
10                     } finally {  
11                         scheduleNext();  
12                     }  
13                 }  
14             });  
15             if (mActive == null) {  
16                 scheduleNext();  
17             }  
18 }  
19   
20         protected synchronized void scheduleNext() {  
21             if ((mActive = mTasks.poll()) != null) {  
22                 THREAD_POOL_EXECUTOR.execute(mActive);  
23             }  
24         }  
25     }  

THREAD_POOL_EXECUTOR 并发线程池

 

asynctask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR); //设置使用 并发线程池 

//params 都是使用在doInBackground(Params... params);

asynctask.executeOnExecutor(executor, params); //可以自定义 线程池     使用这两种方法

Android AsyncTask 分析内部实现