原文链接:https://blog.csdn.net/weixin_43168010/article/details/97613895

之前工作中发现有同事在使用线程池的时候经常搞混淆ThreadPoolTaskExecutor和ThreadPoolExecutor,座椅在这里想写一片博客来讲讲这两个线程池的区别以及使用

ThreadPoolExecutor


这个类是JDK中的线程池类,继承自Executor, Executor 顾名思义是专门用来处理多线程相关的一个接口,所有县城相关的类都实现了这个接口,里面有一个execute()方法,用来执行线程,线程池主要提供一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁的额外开销,提高了响应的速度。相关的继承实现类图如下。

一、线程池接口:ExecutorService为线程池接口,提供了线程池生命周期方法,继承自Executor接口,ThreadPoolExecutor为线程池实现类,提供了线程池的维护操作等相关方法,继承自AbstractExecutorService,AbstractExecutorService实现了ExecutorService接口。

二、线程池的体系结构:
java.util.concurrent.Executor 负责线程的使用和调度的根接口
|—ExecutorService 子接口: 线程池的主要接口
|—ThreadPoolExecutor 线程池的实现类
|—ScheduledExceutorService 子接口: 负责线程的调度
|—ScheduledThreadPoolExecutor : 继承ThreadPoolExecutor,实现了ScheduledExecutorService

三、工具类 : Executors

Executors为线程迟工具类,相当于一个工厂类,用来创建合适的线程池,返回ExecutorService类型的线程池。有人如下方法。
ExecutorService newFixedThreadPool() : 创建固定大小的线程池
ExecutorService newCachedThreadPool() : 缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。
ExecutorService newSingleThreadExecutor() : 创建单个线程池。 线程池中只有一个线程

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

其中AbstractExecutorService是他的抽象父类,继承自ExecutorService,ExecutorService 接口扩展Executor接口,增加了生命周期方法。

实际应用中我一般都比较喜欢使用Exectuors工厂类来创建线程池,里面有五个方法,分别创建不同的线程池,如上,创建一个制定大小的线程池,Exectuors工厂实际上就是调用的ExectuorPoolService的构造方法,传入默认参数。

  1. public class Executors {
  2. /**
  3. * Creates a thread pool that reuses a fixed number of threads
  4. * operating off a shared unbounded queue. At any point, at most
  5. * {@code nThreads} threads will be active processing tasks.
  6. * If additional tasks are submitted when all threads are active,
  7. * they will wait in the queue until a thread is available.
  8. * If any thread terminates due to a failure during execution
  9. * prior to shutdown, a new one will take its place if needed to
  10. * execute subsequent tasks. The threads in the pool will exist
  11. * until it is explicitly {@link ExecutorService#shutdown shutdown}.
  12. *
  13. * @param nThreads the number of threads in the pool
  14. * @return the newly created thread pool
  15. * @throws IllegalArgumentException if {@code nThreads <= 0}
  16. */
  17. public static ExecutorService newFixedThreadPool(int nThreads) {
  18. return new ThreadPoolExecutor(nThreads, nThreads,
  19. 0L, TimeUnit.MILLISECONDS,
  20. new LinkedBlockingQueue<Runnable>());
  21. }
  22. /**
  23. * Creates a thread pool that maintains enough threads to support
  24. * the given parallelism level, and may use multiple queues to
  25. * reduce contention. The parallelism level corresponds to the
  26. * maximum number of threads actively engaged in, or available to
  27. * engage in, task processing. The actual number of threads may
  28. * grow and shrink dynamically. A work-stealing pool makes no
  29. * guarantees about the order in which submitted tasks are
  30. * executed.
  31. *
  32. * @param parallelism the targeted parallelism level
  33. * @return the newly created thread pool
  34. * @throws IllegalArgumentException if {@code parallelism <= 0}
  35. * @since 1.8
  36. */
  37. public static ExecutorService newWorkStealingPool(int parallelism) {
  38. return new ForkJoinPool
  39. (parallelism,
  40. ForkJoinPool.defaultForkJoinWorkerThreadFactory,
  41. null, true);
  42. }

当然,我们也可以直接new ThreadPoolExecutor的构造方法来创建线程池,传入需要的参数。

ThreadPoolTaskExecutor

这个类则是spring包下的,是sring为我们提供的线程池类,这里重点讲解这个类的用法,可以使用基于xml配置的方式创建

  1. <!-- spring线程池 -->
  2. <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
  3. <!-- 核心线程数 -->
  4. <property name="corePoolSize" value="10"/>
  5. <!-- 最大线程数 -->
  6. <property name="maxPoolSize" value="200"/>
  7. <!-- 队列最大长度 >=mainExecutor.maxSize -->
  8. <property name="queueCapacity" value="10"/>
  9. <!-- 线程池维护线程所允许的空闲时间 -->
  10. <property name="keepAliveSeconds" value="20"/>
  11. <!-- 线程池对拒绝任务(无线程可用)的处理策略 -->
  12. <property name="rejectedExecutionHandler">
  13. <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/>
  14. </property>
  15. </bean>

然后通过自动注入的方式注入线程池,

  1. @Resource(name="taskExecutor")
  2. ThreadPoolTaskExecutor taskExecutor;
  3. // 或者可以直接@Autowried
  4. @AutoWired
  5. ThreadPoolTaskExecutor taskExecutor


或者是通过配置类的方式配置线程池,然后注入。

  1. @Configuration
  2. public class ExecturConfig {
  3. @Bean("taskExector")
  4. public Executor taskExector() {
  5. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  6. int i = Runtime.getRuntime().availableProcessors();//获取到服务器的cpu内核
  7. executor.setCorePoolSize(5);//核心池大小
  8. executor.setMaxPoolSize(100);//最大线程数
  9. executor.setQueueCapacity(1000);//队列程度
  10. executor.setKeepAliveSeconds(1000);//线程空闲时间
  11. executor.setThreadNamePrefix("tsak-asyn");//线程前缀名称
  12. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());//配置拒绝策略
  13. return executor;
  14. }

上面注解中已经注释了参数的详解,这里重点讲解一下spring线程池的拒绝策略和处理流程。

拒绝策略

rejectedExectutionHandler参数字段用于配置绝策略,常用拒绝策略如下
AbortPolicy:用于被拒绝任务的处理程序,它将抛出RejectedExecutionException
CallerRunsPolicy:用于被拒绝任务的处理程序,它直接在execute方法的调用线程中运行被拒绝的任务。
DiscardOldestPolicy:用于被拒绝任务的处理程序,它放弃最旧的未处理请求,然后重试execute。
DiscardPolicy:用于被拒绝任务的处理程序,默认情况下它将丢弃被拒绝的任务。

处理流程


1.查看核心线程池是否已满,不满就创建一条线程执行任务,否则执行第二步。
2.查看任务队列是否已满,不满就将任务存储在任务队列中,否则执行第三步。
3.查看线程池是否已满,即就是是否达到最大线程池数,不满就创建一条线程执行任务,否则就按照策略处理无法执行的任务。

流程图如下
image.png
总结:本篇文章主要讲了一下JDK线程池和spring线程池这两个线程池,具体实际业务则和平时使用一样。