【发布时间】:2016-06-20 22:54:09
【问题描述】:
这里我调用了三个线程,第二个和第三个线程等待第一个线程完成,然后开始并行执行。如果我使用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;
}
输出
executor.shutdown()
In main
Exiting main
11111
没有
executor.shutdown()的输出
In main
Exiting main
111113535353535
But the program doesn't terminates.
【问题讨论】:
-
我会尝试将最终任务添加到 CompletableFuture
.thenRun(() -> { executor.shutdown(); }); -
谢谢你,它的工作。您能否将其发布为答案,以便我接受。
标签: java multithreading