当前位置:   article > 正文

springboot中的线程池_springboot默认线程池

springboot默认线程池

1.springboot线程池定时任务类org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler

参考springboot线程池任务调度类 -- ThreadPoolTaskScheduler介绍 - toiletgg - 博客园

ThreadPoolTaskScheduler其实底层使用也是java自带的线程池,相比于通过java自带的周期性任务线程池ScheduleThreadPoolExecutor,此bean对象支持根据cron表达式创建周期性任务。

当在启动类添加@EnableScheduling注解,启动时会默认创建ThreadPoolTaskScheduler类,但默认线程池只有1,可以自己手动创建,那会覆盖框架自动创建的类。

  1. @Bean
  2. public TaskScheduler taskScheduler() {
  3. ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
  4. taskScheduler.setPoolSize(2);//我这里设置的线程数是2,可以根据需求调整
  5. return taskScheduler;
  6. }

方法如下 

 org.springframework.scheduling.TaskScheduler#schedule(java.lang.Runnable, java.time.Instant),是延迟执行一次

org.springframework.scheduling.TaskScheduler#schedule(java.lang.Runnable, org.springframework.scheduling.Trigger)是cron表达式定时执行

参考动态创建线程池:SpringBoot设置动态定时任务_wl_Honest的博客-CSDN博客_springboot动态定时任务

2.springboot线程池非定时任务类ThreadPoolTaskExecutor

参考:@EnableAsync@Async使用总结 - 在贝加尔湖畔 - 博客园

我们在使用多线程的时候,往往需要创建Thread类,或者实现Runnable接口,如果要使用到线程池,我们还需要来创建Executors,在使用spring中,已经给我们做了很好的支持。只要要@EnableAsync就可以使用多线程。使用@Async就可以定义一个线程任务。通过spring给我们提供的ThreadPoolTaskExecutor就可以使用线程池。 

  1. @Configuration
  2. @EnableAsync
  3. public class ThreadPoolTaskConfig {
  4. private static final int corePoolSize = 10; // 核心线程数(默认线程数)
  5. private static final int maxPoolSize = 100; // 最大线程数
  6. private static final int keepAliveTime = 10; // 允许线程空闲时间(单位:默认为秒)
  7. private static final int queueCapacity = 200; // 缓冲队列数
  8. private static final String threadNamePrefix = "Async-Service-"; // 线程池名前缀
  9. @Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
  10. public ThreadPoolTaskExecutor getAsyncExecutor(){
  11. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  12. executor.setCorePoolSize(corePoolSize);
  13. executor.setMaxPoolSize(maxPoolSize);
  14. executor.setQueueCapacity(queueCapacity);
  15. executor.setKeepAliveSeconds(keepAliveTime);
  16. executor.setThreadNamePrefix(threadNamePrefix);
  17. // 线程池对拒绝任务的处理策略
  18. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  19. // 初始化
  20. executor.initialize();
  21. return executor;
  22. }
  23. }

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

闽ICP备14008679号