在开发Spring Boot应用程序时,定时任务是一项常见的需求。Spring Boot提供了@Scheduled
注解,可用于将方法标记为定时任务,并在预定的时间间隔内执行。那么@Scheduled
注解的执行方式是单线程执行,还是多线程执行?@Scheduled
注解的执行方式会不会产生线程不安全的问题?
以下总结@Scheduled
注解的执行方式,并解释它在Spring Boot中的多线程行为。
一:案例演示
新建两个定时任务,一个是每2秒执行一次,一个是每3秒执行一次
@Component
public class ScheduledTest {
@Scheduled(cron = "0/2 * * * * ? ")
public void testTask1(){
Thread thread = Thread.currentThread();
String threadName = thread.getName();
System.out.println(threadName+"-->"+ "testTask1-->"+LocalDateTime.now());
}
@Scheduled(cron = "0/3 * * * * ? ")
public void testTask2(){
Thread thread = Thread.currentThread();
String threadName = thread.