当前位置:   article > 正文

ThreadPoolTaskExecutor和ThreadPoolExecutor区别

threadpooltaskexecutor和threadpoolexecutor区别

1.ThreadPoolTaskExecutor和ThreadPoolExecutor区别

ThreadPoolTaskExecutor是spring core包中的,而ThreadPoolExecutor是JDK中的JUC。

ThreadPoolTaskExecutor是对ThreadPoolExecutor进行了封装处理。

ThreadPoolExecutor结构,祖类都是调用Executor接口:

ThreadPoolTaskExecutor结构,祖类都是调用Executor接口:

在这里插入图片描述

2.工具类 : Executors 

Executors为线程池工具类,相当于一个工厂类,用来创建合适的线程池,返回ExecutorService类型的线程池。有如下方法:

ExecutorService newFixedThreadPool() : 创建固定大小的线程池


ExecutorService newCachedThreadPool() : 缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。


ExecutorService newSingleThreadExecutor() : 创建单个线程池。 线程池中只有一个线程

ScheduledExecutorService newScheduledThreadPool() : 创建可以执行延迟或定时任务的线程池
 

3.ThreadPoolTaskExecutor和ThreadPoolExecutor以及Executors到底该使用哪个?

ThreadPoolTaskExecutor和ThreadPoolExecutor比Executors创建线程池更加灵活,可以设置参数

推荐ThreadPoolTaskExecutor和ThreadPoolExecutor,而ThreadPoolTaskExecutor是ThreadPoolExecutor的封装,所以,性能更加优秀,推荐ThreadPoolTaskExecutor

4.这是ThreadPoolTaskExecutor用来初始化threadPoolExecutor的方法,BlockingQueue是一个阻塞队列,这个我们先不管。由于ThreadPoolTaskExecutor的实现方式完全是使用threadPoolExecutor进行实现,我们需要知道这个threadPoolExecutor的一些参数。

ThreadPoolExecutor的:

  1. public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport implements SchedulingTaskExecutor {
  2. private final Object poolSizeMonitor = new Object();
  3. private int corePoolSize = 1;
  4. private int maxPoolSize = 2147483647;
  5. private int keepAliveSeconds = 60;
  6. private boolean allowCoreThreadTimeOut = false;
  7. private int queueCapacity = 2147483647;
  8. private ThreadPoolExecutor threadPoolExecutor; //这里就用到了ThreadPoolExecutor

ThreadPoolTaskExecutor的:

  1. public ThreadPoolExecutor(int corePoolSize,
  2. int maximumPoolSize,
  3. long keepAliveTime,
  4. TimeUnit unit,
  5. BlockingQueue<Runnable> workQueue,
  6. ThreadFactory threadFactory,
  7. RejectedExecutionHandler handler) {
  8. if (corePoolSize < 0 ||
  9. maximumPoolSize <= 0 ||
  10. maximumPoolSize < corePoolSize ||
  11. keepAliveTime < 0)
  12. throw new IllegalArgumentException();
  13. if (workQueue == null || threadFactory == null || handler == null)
  14. throw new NullPointerException();
  15. this.corePoolSize = corePoolSize;
  16. this.maximumPoolSize = maximumPoolSize;
  17. this.workQueue = workQueue;
  18. this.keepAliveTime = unit.toNanos(keepAliveTime);
  19. this.threadFactory = threadFactory;
  20. this.handler = handler;
  21. }

参数说明:

    1、corePoolSize:核心线程数 (corePoolSize = cpu核心数 * 2 + 有效磁盘数)
 
    2、queueCapacity:任务队列容量(阻塞队列)
 
    3、maxPoolSize:最大线程数
       
    4、 keepAliveTime:线程空闲时间
 
    5、allowCoreThreadTimeout:允许核心线程超时 


    6、rejectedExecutionHandler:任务拒绝处理器
        * 两种情况会拒绝处理任务:
            - 当线程数已经达到maxPoolSize,切队列已满,会拒绝新任务
            - 当线程池被调用shutdown()后,会等待线程池里的任务执行完毕,再shutdown。如果在调用shutdown()和线程池真正shutdown之间提交任务,会拒绝新任务
        * 线程池会调用rejectedExecutionHandler来处理这个任务。如果没有设置默认是AbortPolicy,会抛出异常
        * ThreadPoolExecutor类有几个内部实现类来处理这类情况:
            - AbortPolicy 直接抛出java.util.concurrent.RejectedExecutionException异常
            - CallerRunsPolicy 若已达到待处理队列长度,将由主线程直接处理请求
            - DiscardPolicy 抛弃当前任务;会导致被丢弃的任务无法再次被执行
            - DiscardOldestPolicy 抛弃旧的任务;会导致被丢弃的任务无法再次被执行
        * 实现RejectedExecutionHandler接口,可自定义处理器

execute和submit的区别

提交任务类型

        execute和submitsubmitsubmit都属于线程池的方法,execute只能提交Runnable类型的任务

        submit既能提交Runnable类型任务也能提交Callable类型任务。

返回值

        execute()没有返回值

        submit有返回值,所以需要返回值的时候必须使用submit

        注意:submit的返回值为Future<?>,可通过get获取其泛型。Future<?>对象.get()方法具有阻塞当前线程的做用(也就是谁调用Future<?>对象.get()就阻塞谁,防止主线程在拿返回值时,而子线程还没有执行完)

线程池配置

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.scheduling.annotation.EnableAsync;
  4. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  5. import java.util.concurrent.Executor;
  6. import java.util.concurrent.ThreadPoolExecutor;
  7. @Configuration
  8. public class ThreadPoolConfig {
  9. //获取cpu核心数
  10. private final static int AVAILABLE_PROCESSOR = Runtime.getRuntime().availableProcessors();
  11. /**
  12. * 通用线程池配置
  13. */
  14. @Bean("taskPoolExecutor")
  15. public Executor taskExecutor() {
  16. ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
  17. //设置核心线程数
  18. taskExecutor.setCorePoolSize(6);
  19. //设置最大线程数
  20. taskExecutor.setMaxPoolSize(6*2);
  21. //设置队列最大容量
  22. taskExecutor.setQueueCapacity(12);
  23. //设置线程空闲时间(秒)
  24. taskExecutor.setKeepAliveSeconds(60);
  25. //设置线程名称前缀
  26. taskExecutor.setThreadNamePrefix("taskPoolExecutor--");
  27. //调度器shutdown方法被调用时等待当前被调度的任务完成
  28. taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
  29. //等待时间(秒)
  30. taskExecutor.setAwaitTerminationSeconds(60);
  31. //拒绝策略
  32. taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
  33. //初始化线程池
  34. taskExecutor.initialize();
  35. return taskExecutor;
  36. }
  37. /**
  38. * 发送短信线程池
  39. * @return
  40. */
  41. @Bean("sendSmsThreadPool")
  42. public Executor sendSmsThreadPool() {
  43. ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
  44. //设置线程池参数信息
  45. taskExecutor.setCorePoolSize(AVAILABLE_PROCESSOR);
  46. taskExecutor.setMaxPoolSize(AVAILABLE_PROCESSOR + 1);
  47. taskExecutor.setQueueCapacity(256);
  48. taskExecutor.setKeepAliveSeconds(20);
  49. taskExecutor.setThreadNamePrefix("sendSmsThreadPool--");
  50. taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
  51. taskExecutor.setAwaitTerminationSeconds(60);
  52. //修改拒绝策略为使用当前线程执行
  53. taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  54. //初始化线程池
  55. taskExecutor.initialize();
  56. return taskExecutor;
  57. }
  58. /**
  59. * 发送邮件线程池
  60. * @return
  61. */
  62. @Bean("sendEmailThreadPool")
  63. public Executor sendEmailThreadPool() {
  64. ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
  65. //设置线程池参数信息
  66. taskExecutor.setCorePoolSize(AVAILABLE_PROCESSOR);
  67. taskExecutor.setMaxPoolSize(AVAILABLE_PROCESSOR + 1);
  68. taskExecutor.setQueueCapacity(256);
  69. taskExecutor.setKeepAliveSeconds(20);
  70. taskExecutor.setThreadNamePrefix("sendEmailThreadPool--");
  71. taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
  72. taskExecutor.setAwaitTerminationSeconds(60);
  73. //修改拒绝策略为使用当前线程执行
  74. taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  75. //初始化线程池
  76. taskExecutor.initialize();
  77. return taskExecutor;
  78. }
  79. @Bean(name = "threadPoolTaskExecutor")
  80. public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
  81. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  82. executor.setCorePoolSize(5);
  83. executor.setMaxPoolSize(5);
  84. executor.setQueueCapacity(10);
  85. executor.setKeepAliveSeconds(300);
  86. executor.setThreadNamePrefix("thread-ayokredit"); //线程名称
  87. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  88. return executor;
  89. }
  90. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/104683
推荐阅读
  

闽ICP备14008679号