ThreadPoolTask​​Scheduler如何使每个未来异步

时间:2019-01-02 03:25:36

标签: java spring

自动连接线程池任务计划:

@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
    threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    threadPoolTaskScheduler.setPoolSize(10);
    return threadPoolTaskScheduler;
}

未来测试:

public void test(){
    ScheduledFuture future = threadPoolTaskScheduler.schedule(new MyFuture(), new CronTrigger("0/5 * * * * ?"));
}
private class MyFuture implements Runnable{
    @Override
    public void run() {
       int a=0;
       for(int i=0;i<1000000;i++){
          for(int j=0;j<1000000;j++){
              a++;
          }
       }
    }
}

当我运行test()时,我发现第一个线程正在运行,但是时间超过5s,第二个线程没有运行,正在等待第一个线程完成。现在如何让线程异步执行并不等待最后一个线程完成? enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

CronTrigger的JavaDoc说

/**
 * Determine the next execution time according to the given trigger context.
 * <p>Next execution times are calculated based on the
 * {@linkplain TriggerContext#lastCompletionTime completion time} of the
 * previous execution; therefore, overlapping executions won't occur.
 */

因此因此,执行不会重叠。 如果您确实需要重叠的任务,则需要采取一些解决方法。