springboot中schedule定时任务是一个线程管理的么

无论有多少个定时任务,都是由一个线程来管理。
验证办法:
如果是一个线程,不同的schedule之间会等待。 如果是多个线程,不同的schedule之间不会等待。

如下代码说明用法:

@SpringBootApplication
@EnableScheduling
public class AccessingDataMysqlApplication {
    public static void main(String[] args) {
        ApplicationContext app = SpringApplication.run(AccessingDataMysqlApplication.class, args);

    }
    @Scheduled(cron = "0/2 * * * * ?")
    public void schedule1(){
        try {
            System.out.println(Thread.currentThread().getName()+", 1 "+Instant.now());
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName()+" 1 end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0/2 * * * * ?")
    public void schedule2(){
        try {
            System.out.println(Thread.currentThread().getName()+", 2  "+ Instant.now());
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName()+" 2  end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

输出为:

pool-1-thread-1, 2  2020-02-08T14:21:46.001Z
pool-1-thread-1 2  end
pool-1-thread-1, 1 2020-02-08T14:21:51.002Z
pool-1-thread-1 1 end
pool-1-thread-1, 2  2020-02-08T14:21:56.002Z
pool-1-thread-1 2  end
pool-1-thread-1, 1 2020-02-08T14:22:01.003Z
pool-1-thread-1 1 end
pool-1-thread-1, 2  2020-02-08T14:22:06.076Z

如果是多线程,同序号线程应该5秒输出一次。
但是发现都收到影响了,所以定时任务是一个线程管理的。

发布了422 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/enthan809882/article/details/104229402