gpt4 book ai didi

Java:CompletableFuture.supplyAsync() 不调用异步方法

转载 作者:行者123 更新时间:2023-11-30 02:11:09 26 4
gpt4 key购买 nike

让我们假设以下主要方法:

public class Async {
public static void main(String[] args) throws Exception {

CompletableFuture.supplyAsync(Async::sendMsg);
System.out.println(Thread.currentThread().getName());


}

public static String sendMsg() {
try {
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}

我只想进行异步调用而不阻塞主线程。但控制台只输出以下字符串:

main

sendMsg的输出- 方法似乎没有被调用。但为什么?我错过了什么吗?

最佳答案

因为CompletableFuture.supplyAsync(Supplier)使用 common ForkJoinPool一旦程序(主线程)终止,任务就会自动终止。

关于Java:CompletableFuture.supplyAsync() 不调用异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50071510/

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