java - 主线程在 CompletableFuture 完成之前退出

标签 java multithreading asynchronous

    CompletableFuture feature = CompletableFuture.supplyAsync (() ->       composeMethod ( )).
            thenAccept (s -> System.out.println ("wassup java" + s)).
            thenRun (() -> System.out.println (" imm immortal"));
    nonblockingmethod ( );

这是我正在处理的 CompletableFuture future 示例

private static void nonblockingmethod() {
        System.out.println ("why  should i wait for you ");
    }

    private static String composeMethod() {
        try {
            TimeUnit.MILLISECONDS.sleep (3);
            File file = Paths.get ("/Users/solo/solo1.txt").toFile ( );

            if (!file.exists ( )) {
                file.createNewFile ( );
            }

        } catch (Exception e) {

        }
        return "   resultdaa";
    }

首先,我从 supplyAsync 调用 compose 方法,在其中执行 composeMethod 方法,有一个三毫秒的延迟,然后它将创建一个文件并返回一个字符串作为结果。完成后我调用 thenRun 方法,它只打印一个方法,之后有一个从主线程运行的非阻塞方法。

我在这里面临的问题是主线程完成执行 nonblockingmethod() 并在 3 毫秒延迟之前退出进程,而后续操作来自 composeMethod。这是预期的行为还是我必须使用 get 或 join 阻塞主线程,否则我会错过任何东西

最佳答案

supplyAsync 中提供的任务将在 ForkJoinPool#commonPool 中执行。如果你看一下 common pool 中的线程,你会发现它们是 Deamon thread,这意味着 JVM 不会等待当没有 active non-daemon thread 时关闭该守护线程以完成其执行。在您的情况下,您在 composeMethod 中 hibernate ,与此同时,主线程执行并完成其工作,JVM 没有任何 Activity 的非守护线程。因此,JVM 将进入关闭,而不等待您的任务完成。如果运行以下示例,您可以确认线程池和线程类型。

CompletableFuture feature = CompletableFuture.supplyAsync(() -> {
    System.out.println("Thread : " + Thread.currentThread());
    System.out.println("Is Daemon : " + Thread.currentThread().isDaemon());
    return composeMethod();
}).thenAccept(s -> System.out.println("wassup java" + s)).thenRun(() -> System.out.println(" imm immortal"));

输出:

Thread : Thread[ForkJoinPool.commonPool-worker-1,5,main] // This line may be bit different but it indicates that your task is executing on Common pool
Is Daemon : true
why  should i wait for you 

To resolve the issue you can pass your own executor like below:

ExecutorService executorService = Executors.newFixedThreadPool(8);
CompletableFuture feature = CompletableFuture.supplyAsync(() -> {
        System.out.println("Thread : " + Thread.currentThread());
        System.out.println("Is Daemon : " + Thread.currentThread().isDaemon());
        return composeMethod();
    }, executorService).thenAccept(s -> System.out.println("wassup java" + s))
            .thenRun(() -> System.out.println(" imm immortal"));
executorService.shutdown();
nonblockingmethod();

输出:

Thread : Thread[pool-1-thread-1,5,main]
Is Daemon : false
why  should i wait for you 
wassup java   resultdaa
 imm immortal

关于java - 主线程在 CompletableFuture 完成之前退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55267451/

相关文章:

java - Java-同步和启动线程

mysql - Node.js 不等待 MySQL 服务器发送应答,继续异步工作

java - 测验应用程序 - 循环问题

java - Thread.stop 和 friend 在 Java 中安全吗?

Java 线程中断标志被清除

android - 位图到可以通过异步上传的文件

javascript - 在导出之前加载异步配置

java - 具有 <ui :repeat> 的不同 div 标签 id

java - 使用 JFileChooser() 和 JButton() 重命名文件/目录

c++ - 在微服务C++中运行gRPC服务器