当前位置:   article > 正文

ThreadPoolTaskExecutor和ThreadPoolExecutor介绍

threadpooltaskexecutor和threadpoolexecutor

使用场景:开发中,经常有一些非主流程业务要处理,为了提升主业务处理速度,可使用线程池来异步处理.例如,开户之后的通知任务.

1,ThreadPoolTaskExecutor

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

  1. <bean id="callerRunsPolicy" class="java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy"/>
  2. <!-- 线程池 -->
  3. <bean id="taskExecutor"
  4. class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
  5. <!-- 线程池维护线程的最少数量 -->
  6. <property name="corePoolSize" value="10"/>
  7. <!-- 线程池维护线程所允许的空闲时间 -->
  8. <property name="keepAliveSeconds" value="3000"/>
  9. <!-- 线程池维护线程的最大数量 -->
  10. <property name="maxPoolSize" value="100"/>
  11. <!-- 线程池所使用的缓冲队列 -->
  12. <property name="queueCapacity" value="200000"/>
  13. <!-- 阻塞机制 -->
  14. <property name="rejectedExecutionHandler" ref="callerRunsPolicy"/>
  15. </bean>

注:ThreadPoolTaskExecutor中的excute和submit方法的区别?

无返回值的任务使用execute方法提交;

有返回值的任务使用submit(Callable) 方法提交

使用submit提交任务,提交后只要有从Future取数据的操作,那么主线程在子线程结束后才会结束.

 

 

2,ThreadPoolExecutor

这个类是JDK中的线程池类,继承自Executor,里面有一个execute()方法,用来执行线程,线程池主要提供一个线程队列,队列中保存着所有等待状态的线程。

使用方式有两种,可以通过工具类或者构造方法.

  1. 方式一:构造方法(传入相应的参数即可).
  2. private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 300, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1200), new DiscardOldestPolicy());
  1. 方式二:通过Executors工具类.
  2. Executors类,提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口.
  3. 1public static ExecutorService newFiexedThreadPool(int Threads)
  4.  创建固定数目线程的线程池。
  5. 2public static ExecutorService newCachedThreadPool()
  6. 创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果没有可用的线程,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
  7. 3public static ExecutorService newSingleThreadExecutor()
  8. 创建一个单线程化的Executor。
  9. 4public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
  10. 创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。


 

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/104693
推荐阅读
  

闽ICP备14008679号