gpt4 book ai didi

java - 为什么 ExecutorService 等待所有线程完成但 Completablefuture 没有?

转载 作者:行者123 更新时间:2023-12-04 07:23:52 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





CompletableFuture is not getting executed. If I use the ExecutorService pool it works as expected but not with the common ForkJoinPool

(1 个回答)


10 个月前关闭。




在以下代码中,

class MainX {

static void run(int i) {
try {
System.out.println(i + " called");
Thread.sleep(1000);
String s = "";
for (int j = 0; j < 20000; j++) {
s = s + j;
}
System.out.println(i + " completed" + " " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
int p = i;
executorService.submit(() -> MainX.run(p));
}
System.out.println("all called");
executorService.shutdown();
System.out.println("all called" + " Thr:" + Thread.currentThread().getName());
}
}
(对比)
class MainX {

static void run(int i) {
try {
System.out.println(i + " called");
Thread.sleep(1000);
String s = "";
for (int j = 0; j < 20000; j++) {
s = s + j;
}
System.out.println(i + " completed" + " " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
int p = i;
CompletableFuture.runAsync(() -> MainX.run(p));
}
}
}
在第一种情况下,jvm 会继续运行,直到所有线程都完成。但在第二种情况下,一旦主线程死亡,jvm 和其他线程就会被杀死。
这有什么原因吗?

最佳答案

从我的角度来看,“CompletableFuture”本身并不执行任何操作,因此它没有等待线程。它依赖于其他机制来运行阶段。
'runAsync',没有 Executor,在其公共(public) ForkJoin 池中运行任务,即 documented就像你观察到的行为一样。
这并不能回答您关于“为什么”的问题,只是说它是故意这样设计的。我只能挥手说它的设计师可能认为它是最好的默认选择。
(我同意:在我编写的代码中,如果我到达程序终止的地步,我想要的就是让一切都消失。在极少数情况下我需要它完成,我会在退出之前等待它.)

关于java - 为什么 ExecutorService 等待所有线程完成但 Completablefuture 没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68327956/

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