Java: CompletableFuture.supplyAsync() 不调用异步方法
Java: CompletableFuture.supplyAsync() do no invoke asynchronous method
让我们假设以下主要方法:
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) uses the common ForkJoinPool一旦程序(主线程)终止,任务就会自动终止。
让我们假设以下主要方法:
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) uses the common ForkJoinPool一旦程序(主线程)终止,任务就会自动终止。