gpt4 book ai didi

java8异步方法CompletableFuture.runAsync不运行

转载 作者:行者123 更新时间:2023-12-02 09:20:34 25 4
gpt4 key购买 nike

运行异步方法的非常基本的代码。当我运行以下代码时,runAsync 不会运行。我缺少什么?

结果仅运行同步代码。

public class Main {

public static void main(String[] args) {
runAsync("run async command ans wait 10000");

System.out.println("sync commands ");
}

public static void runAsync(String inputStr) {

CompletableFuture.runAsync(() -> {
List<String> strings = Arrays.asList(inputStr.split(" "));
int sleep = Integer.parseInt(strings.get(strings.size() - 1));
try {
sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("async command ");
});

}
}

我希望首先获得“同步命令”,然后获得“异步命令”但只获取同步消息

最佳答案

您的任务将在其他线程中运行(默认情况下在ForkJoinPoolThread中运行),并且您无需等待它完成- 主线程在异步任务执行/提交之前结束。您可以调用CompletableFuture::join等待它完成,它将阻塞主线程直到它完成:

CompletableFuture.runAsync(() -> {
List<String> strings = Arrays.asList(inputStr.split(" "));
int sleep = Integer.parseInt(strings.get(strings.size() - 1));
try {
sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("async command ");
}).join(); //here call the join

或类似:

CompletableFuture<Void> cf = CompletableFuture.runAsync(() -> {
//...
});

cf.join();

关于java8异步方法CompletableFuture.runAsync不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58725491/

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