为什么 Spring Boot 中使用 ExecutorCompletionService

我使用 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();

         }

}


守着一只汪
浏览 48回答 1
1回答

FFIVE

get()因为您在提交第二个作业之前就阻止了第一个作业的调用。submit get submit get如果你想让它们并行运行,你需要这样做submit submit get get
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java