为什么使用ExecutorCompletionService的Spring Boot中的线程不会并行启动?

问题描述 投票:0回答:1

我将Spring Boot版本2.1.9.RELEASE与Java 1.8一起使用,并且有两个我希望并行启动的lang运行进程。因此,我决定使用线程。当我启动sumResult方法时,第二个线程首先启动,第一个线程等待直到第二个线程完成。

为什么这两个线程不能同时启动,或者彼此之间起码要短一些?

private void sumResult(String year, String month, String day) throws 
    ExecutionException, InterruptedException {
         ExecutorCompletionService<Boolean> completionService = new 
         ExecutorCompletionService<>(Executors.newCachedThreadPool());

         // First thread
         mut.initialise(year, month, day);
         boolean mutCompleted = completionService.submit(
               ()-> mut.sum(),true).get();

         // Second thread
         apt.initialise(year, month, day);
         boolean aptCompleted = completionService.submit(
              ()-> apt.sum(), true).get();

         // On completion of both thread
         if(mutCompleted && aptCompleted ){
              mixAndPrint();
         }

}

java multithreading spring-boot executorservice threadpoolexecutor
1个回答
1
投票

因为在提交第二份作业之前,您将阻止在第一份作业上调用get()

submit
get
submit
get

如果您希望它们并行运行,则需要这样做

submit
submit
get
get
© www.soinside.com 2019 - 2024. All rights reserved.