Spring注解@Scheduled 多线程异步执行

一、前言: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 ;

        }

   }

猜你喜欢

转载自www.cnblogs.com/xnfTosharing/p/12468120.html