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

Zee*_*han 0 java multithreading

这里我调用三个线程,第二个和第三个线程等待第一个线程完成,然后开始并行执行.如果我使用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;

    }
Run Code Online (Sandbox Code Playgroud)

输出 executor.shutdown()

In main
Exiting main
11111
Run Code Online (Sandbox Code Playgroud)

没有输出 executor.shutdown()

In main
Exiting main
111113535353535
But the program doesn't terminates.
Run Code Online (Sandbox Code Playgroud)

Nad*_*dir 5

我会尝试在CompletableFuture中添加一个最终任务

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