【问题标题】:Will the main thread exiting kill the Async task?主线程退出会杀死异步任务吗?
【发布时间】:2017-05-06 16:07:36
【问题描述】:

我正在运行java8应用程序,看起来一旦主线程退出,进程就会退出。

我正在使用 completableFuture 启动如下异步任务

CompletableFuture cf = CompletableFuture.supplyAsync(() -> task.call());

        cf.thenRunAsync(() -> {
            try {
                System.out.println(Thread.currentThread());
                System.out.println((Double)cf.get() * 4.0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });

我希望 async 将作为单独的线程运行,因此主线程退出不应导致进程退出,但事实证明并非如此。

我猜异步作业是作为守护线程运行的?但无法确认。

【问题讨论】:

  • 您能否详细说明您的问题?
  • 添加代码sn-p

标签: java multithreading


【解决方案1】:

如上所述here

方法supplyAsync使用ForkJoinPool.commonPool()线程池 共享给所有CompletableFutures

正如提到的here

ForkJoinPool 在守护模式下使用线程,通常不需要 在程序退出时显式关闭这样的池。

看来是这样的。

为避免这种情况,您需要传递一个显式执行器,例如:

ExecutorService pool = Executors.newFixedThreadPool(5);
final CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                ... }, pool);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 2018-11-26
    • 2013-05-29
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多