Reputation: 12431
Here I am invoking three threads, the second and third threads waits for the first thread to complete and then starts executing in parallel. If I use executor.shutdown()
then only the first task executes. I want to know how to shutdown executor after all my threads are done executing
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.
Upvotes: 3
Views: 5408
Reputation: 1819
I would try by adding a final task to the CompletableFuture
.thenRun(() -> { executor.shutdown(); });
Upvotes: 9