【问题标题】:How do I shut down executor when using it with CompletableFuture与 CompletableFuture 一起使用时如何关闭执行程序
【发布时间】: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(() -&gt; { executor.shutdown(); });
  • 谢谢你,它的工作。您能否将其发布为答案,以便我接受。

标签: java multithreading


【解决方案1】:

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

.thenRun(() -&gt; { executor.shutdown(); });

【讨论】:

  • 如果我期望来自 supplyAsync 调用而不是 Void 的输出怎么办?
  • 那么你就不会添加这一行了。在单独的一行中,您将执行 thenCompose.get() 来检索结果,然后执行 executor.shutdown()。由于get() 将一直等到CompletableFuture 完成,您可以在之后安全地关闭执行器。
  • 是否推荐shutdown() 或者如果不使用executor.shutdown() 发布get() 会发生什么?
  • @Nobita prolly 行为与 OP 相同,程序永远不会退出。
  • 这里的OP是什么意思?
猜你喜欢
  • 2019-11-14
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多