使用CompletableFuture

时间:2016-03-07 11:45:50

标签: 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;

    }
  

使用executor.shutdown()输出

In main
Exiting main
11111
  

没有executor.shutdown()

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

1 个答案:

答案 0 :(得分:5)

我会尝试将最终任务添加到CompletableFuture

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