springboot中的线程池

2022-08-10 08:36:49

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

参考https://www.cnblogs.com/toiletgg/p/10647436.html

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表达式定时执行

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

参考:https://www.cnblogs.com/hsug/p/13303018.html

我们在使用多线程的时候,往往需要创建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;
	}
}
  • 作者:SomeOtherTime
  • 原文链接:https://blog.csdn.net/yaoct/article/details/119728243
    更新时间:2022-08-10 08:36:49