赞
踩
参考springboot线程池任务调度类 -- ThreadPoolTaskScheduler介绍 - toiletgg - 博客园
ThreadPoolTaskScheduler其实底层使用也是java自带的线程池,相比于通过java自带的周期性任务线程池ScheduleThreadPoolExecutor,此bean对象支持根据cron表达式创建周期性任务。
当在启动类添加@EnableScheduling注解,启动时会默认创建ThreadPoolTaskScheduler类,但默认线程池只有1,可以自己手动创建,那会覆盖框架自动创建的类。
- @Bean
- public TaskScheduler taskScheduler() {
- ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
- taskScheduler.setPoolSize(2);//我这里设置的线程数是2,可以根据需求调整
- return taskScheduler;
- }
方法如下
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动态定时任务
参考:@EnableAsync@Async使用总结 - 在贝加尔湖畔 - 博客园
我们在使用多线程的时候,往往需要创建Thread类,或者实现Runnable接口,如果要使用到线程池,我们还需要来创建Executors,在使用spring中,已经给我们做了很好的支持。只要要@EnableAsync就可以使用多线程。使用@Async就可以定义一个线程任务。通过spring给我们提供的ThreadPoolTaskExecutor就可以使用线程池。
- @Configuration
- @EnableAsync
- public class ThreadPoolTaskConfig {
-
- private static final int corePoolSize = 10; // 核心线程数(默认线程数)
- private static final int maxPoolSize = 100; // 最大线程数
- private static final int keepAliveTime = 10; // 允许线程空闲时间(单位:默认为秒)
- private static final int queueCapacity = 200; // 缓冲队列数
- private static final String threadNamePrefix = "Async-Service-"; // 线程池名前缀
-
- @Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
- public ThreadPoolTaskExecutor getAsyncExecutor(){
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(corePoolSize);
- executor.setMaxPoolSize(maxPoolSize);
- executor.setQueueCapacity(queueCapacity);
- executor.setKeepAliveSeconds(keepAliveTime);
- executor.setThreadNamePrefix(threadNamePrefix);
-
- // 线程池对拒绝任务的处理策略
- executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
- // 初始化
- executor.initialize();
- return executor;
- }
- }

赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。