一、前言:Spring 定時任務@Schedule的使用方式,默認是單線程同步執行的,啟動過程是一個單線程同步啟動過程,一旦中途被阻塞,會導致整個啟動過程阻塞,
其余的定時任務都不會啟動。
二、@Schedule注解多線程的實現:多個定時任務的執行,通過使用@Async注解 來實現多線程異步調用。
@Scheduled(cron = "0/2 * * * * ?") //cron表達式,表示每隔兩秒鍾執行該任務 @Async public void doTask() throws InterruptedException {
System.out.println("當前線程名:"+Thread.currentThread().getName()+"start run Task"); Thread.sleep(6*1000);
System.out.println("當前線程名:"+Thread.currentThread().getName()+"end run Task");
}
解釋:該程序實現了同一任務 多個線程開啟的實現。每個任務之間不受影響,即異步執行。該程序的最大線程池默認是@Async的最大容量 100,有時候我們可能不需要那么多,自己可以通過程序去配置一個線程池數量,如下:
三、配置線程池數量
public class BeanConfig{
@Bean
public TaskScheduler taskScheduler(){
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler .setPoolSize(5);//定義線程池數量為5 個
return taskScheduler ;
}
}