我无法理解用以下方法定义的行为 @Async
注解.根据我的理解,该方法应该每1秒执行一次。但我看到的不是这样。
@EnableAsync
@Component
public class AsyncSchedulingDemo {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//every 1 second, INSTANT start of job but waits for the first job to finish hence takes 10 seconds
//here the next execution will start after 10 seconds because the job takes 10 seconds to finish
@Scheduled(fixedRate = 1000)
public void performFixedRateTask_W_LongRunningJob() throws InterruptedException {
System.out.println("Task performed every 1 second but waits for the first one to finish before the next execution starts " + dateFormat.format(new Date()));
Thread.sleep(10000);
}
//should be executed every 1 second because of @Async
//here the next execution should start IMMEDIATELY and does NOT wait for the first one to finish
@Async
@Scheduled(fixedRate = 1000)
public void performFixedRateTask_With_Async() throws InterruptedException {
System.out.println("Async Task performed every 1 second as it does NOT wait for the first one to finish " + dateFormat.format(new Date()));
Thread.sleep(10000);
}
}
控制台日志。
Task performed every 1 second but waits for the first one to finish before the next execution starts 05/13/2020 15:54:51
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 15:54:51
Task performed every 1 second but waits for the first one to finish before the next execution starts 05/13/2020 15:55:01
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 15:55:01
Task performed every 1 second but waits for the first one to finish before the next execution starts 05/13/2020 15:55:11
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 15:55:11
===UPDATED====
如果我把第一个方法完全注释掉,然后再次执行应用程序,我看到第二个方法每秒钟都在执行。为什么呢?第一个方法是如何阻止第二个方法的执行的?
控制台日志。
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 16:45:48
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 16:45:49
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 16:45:50
Async Task performed every 1 second as it does NOT wait for the first one to finish 05/13/2020 16:45:51
我想,这是因为用于执行方法的线程的默认池大小是1秒。@Scheduled
注释的方法是1,根据 春季文档: "如果不提供'pool-size'属性,默认线程池将只有一个线程。"
由于第一个方法不是 @Async
挡住了唯一的一条线。