gpt4 book ai didi

java - 与 CompletableFuture 一起使用时如何关闭执行程序

转载 作者:行者123 更新时间:2023-12-03 12:48:19 25 4
gpt4 key购买 nike

这里我调用了三个线程,第二个和第三个线程等待第一个线程完成,然后开始并行执行。如果我使用 executor.shutdown(),那么只有第一个任务会执行。我想知道如何在我的所有线程执行完毕后关闭执行器

public static void main(String[] args) {
System.out.println("In main");
ExecutorService executor = Executors.newFixedThreadPool(3);
CompletableFuture<Void> thenCompose = supplyAsync(() -> doTask1(), executor)
.thenCompose(resultOf1 -> allOf(
runAsync(() -> doTask2(resultOf1), executor),
runAsync(() -> doTask3(), executor)
));
//executor.shutdown();
System.out.println("Exiting main");
}

private static void doTask3() {
for(int i=0; i<5;i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(3);
}

}

private static void doTask2(int num) {
for(int i=0; i<5;i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(num);
}

}

private static int doTask1() {
for(int i=0; i<5;i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(1);
}
return 5;

}

Output With executor.shutdown()

In main
Exiting main
11111

Output Without executor.shutdown()

In main
Exiting main
111113535353535
But the program doesn't terminates.

最佳答案

我会尝试向 CompletableFuture 添加最终任务

.thenRun(() -> { executor.shutdown(); });

关于java - 与 CompletableFuture 一起使用时如何关闭执行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35842910/

25 4 0