gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:43:07 26 4
gpt4 key购买 nike

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

}

最佳答案

因为您在提交第二个作业之前就阻止了对第一个作业调用 get()

submit
get
submit
get

如果你想让它们并行运行,你需要这样做

submit
submit
get
get

关于java - 为什么 Spring Boot 中使用 ExecutorCompletionService 的线程不并行启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58555172/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com