Android之AsyncTask两种线程池分析和总结

举报
chenyu 发表于 2021/07/27 01:43:33 2021/07/27
【摘要】 Android AsyncTask两种线程池分析和总结 (一)    前言 在android AsyncTask里面有两种线程池供我们调用 1.    THREAD_POOL_EXECUTOR, 异步线程池 2.    SERIAL_EXECUTOR,同步线程池 正如上面名称描述的那样,一个是异步线程池,多...








(二)     THREAD_POOL_EXECUTOR用法举例


  
  1. private static int produceTaskMaxNumber = 500;
  2. 02
  3. public void dotask(){
  4. 03
  5. for (int i = 1; i <= produceTaskMaxNumber; i++){
  6. 04
  7. // 产生一个任务,并将其加入到线程池
  8. 05
  9. String task = "task@ " + i;
  10. 06
  11. Log.d("Sandy", "put " + task);
  12. 07
  13. MyAsyncTask asynct = new MyAsyncTask(task);
  14. 08
  15. asynct.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 0);
  16. 09
  17. }
  18. 10
  19. }
  20. 11
  21. 12
  22. static class MyAsyncTask extends AsyncTask<Integer, Integer, Integer>{
  23. 13
  24. private static int consumeTaskSleepTime = 2000;
  25. 14
  26. // 保存任务所需要的数据
  27. 15
  28. private Object threadPoolTaskData;
  29. 16
  30. public MyAsyncTask(String s){
  31. 17
  32. threadPoolTaskData = s;
  33. 18
  34. }
  35. 19
  36. <a href="http://home.51cto.com/index.php?s=/space/5017954" target="_blank">@Override</a>
  37. 20
  38. protected Integer doInBackground(Integer... arg0) {
  39. 21
  40. Log.d("Sandy", "start .." + threadPoolTaskData
  41. 22
  42. + " thread id: " + Thread.currentThread().getId()
  43. 23
  44. + " thread name: " + Thread.currentThread().getName());
  45. 24
  46. try {
  47. 25
  48. // //便于观察,等待一段时间
  49. 26
  50. Thread.sleep(consumeTaskSleepTime);
  51. 27
  52. }
  53. 28
  54. catch (Exception e) {
  55. 29
  56. Log.d("Sandy", "", e);
  57. 30
  58. }
  59. 31
  60. threadPoolTaskData = null;
  61. 32
  62. return 0;
  63. 33
  64. }
  65. 34
  66. }


  
  1. MyAsyncTask asynct = new MyAsyncTask(task);
  2. 2
  3. asynct.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 0);

就是因为我们尝试添加500个task到AsyncTask.THREAD_POOL_EXECUTOR线程池中,但是它的核心线程是5,队列容量是128,最大线程数是9。
所以,抛出了这个异常。
那么,接下来的话,我们会去分析这个异常怎么出来的。

(三)     THREAD_POOL_EXECUTOR代码分析
从AsyncTask.THREAD_POOL_EXECUTOR的定义开始分析
1.    代码路径
frameworks\base\core\java\android\os\AsyncTask.java
代码:


  
  1. private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
  2. 02
  3. private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
  4. 03
  5. private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
  6. 04
  7. private static final int KEEP_ALIVE = 1;
  8. 05
  9. 06
  10. ....
  11. 07
  12. /**
  13. 08
  14. * An {@link Executor} that can be used to execute tasks in parallel.
  15. 09
  16. */
  17. 10
  18. public static final Executor THREAD_POOL_EXECUTOR
  19. 11
  20. = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
  21. 12
  22. TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);





  
  1. public ThreadPoolExecutor(int corePoolSize,
  2. 02
  3. int maximumPoolSize,
  4. 03
  5. long keepAliveTime,
  6. 04
  7. TimeUnit unit,
  8. 05
  9. BlockingQueue<Runnable> workQueue,
  10. 06
  11. ThreadFactory threadFactory,
  12. 07
  13. RejectedExecutionHandler handler) {
  14. 08
  15. if (corePoolSize < 0 ||
  16. 09
  17. maximumPoolSize <= 0 ||
  18. 10
  19. maximumPoolSize < corePoolSize ||
  20. 11
  21. keepAliveTime < 0)
  22. 12
  23. throw new IllegalArgumentException();
  24. 13
  25. if (workQueue == null || threadFactory == null || handler == null)
  26. 14
  27. throw new NullPointerException();
  28. 15
  29. this.corePoolSize = corePoolSize;
  30. 16
  31. this.maximumPoolSize = maximumPoolSize;
  32. 17
  33. this.workQueue = workQueue;
  34. 18
  35. this.keepAliveTime = unit.toNanos(keepAliveTime);
  36. 19
  37. this.threadFactory = threadFactory;
  38. 20
  39. this.handler = handler;
  40. 21
  41. }
  42. 22
  43. 23
  44. /**
  45. 24
  46. * The default rejected execution handler
  47. 25
  48. */
  49. 26
  50. private static final RejectedExecutionHandler defaultHandler =
  51. 27
  52. new AbortPolicy();









































1 a.    asynct.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, 0);
2 b.    asynct.execute(0);





01 public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
02             Params... params) {
03         ...
04         exec.execute(mFuture);
05         ....
06 }
07  
08 private static class SerialExecutor implements Executor {
09         final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
10         Runnable mActive;
11         public synchronized void execute(final Runnable r) {
12             mTasks.offer(new Runnable() {
13                 public void run() {
14                     try {
15                         r.run();
16                     } finally {
17                         scheduleNext();
18                     }
19                 }
20             });
21             if (mActive == null) {
22                 scheduleNext();
23             }
24         }
25  
26         protected synchronized void scheduleNext() {
27             if ((mActive = mTasks.poll()) != null) {
28                 THREAD_POOL_EXECUTOR.execute(mActive);
29             }
30         }
31     }


























文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/50494611

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。