gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:10:45 25 4
gpt4 key购买 nike

    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 阻塞主线程,否则我会错过任何东西

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com