[英]Why CompletableFuture 's thenAccept() not running on the main thread
[英]CompletableFuture thenAccept does not work
欢迎,我很困惑为什么这部分代码不起作用。
public class Main {
public static void main(String[] args) throws URISyntaxException {
final String URL = "https://jsonplaceholder.typicode.com/users/1";
HttpRequest request = HttpRequest.newBuilder(new URI(URL)).GET().timeout(Duration.of(10, ChronoUnit.SECONDS)).build();
HttpClient.newHttpClient().sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenAcceptAsync(r -> {
System.out.println(r.statusCode());
System.out.println(Thread.currentThread().getName());
}, Executors.newFixedThreadPool(10));
System.out.println("END OF PROGRAM");
}
}
结果是:
END OF PROGRAM
如果我提供了 ExecutorService JVM 应该等待 CompletableFuture 完成(.thenAceptAsync 部分)但程序立即完成。
大概是我的心态错了。 有人可以解释一下吗?
程序在请求完成之前退出。 该请求使用sendAsync
异步执行,因此它不会阻止程序的执行。
要阻止执行并等待 API 响应,您必须使用response.get();
如下:
public static void main(String[] args) throws URISyntaxException, ExecutionException,
InterruptedException {
final String URL = "https://jsonplaceholder.typicode.com/users/1";
HttpRequest request = HttpRequest.newBuilder(new URI(URL)).GET().timeout(Duration.of(10, ChronoUnit.SECONDS)).build();
CompletableFuture<Void> response = HttpClient.newHttpClient()
.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenAcceptAsync(r -> {
System.out.println(r.statusCode());
System.out.println(Thread.currentThread().getName());
}, Executors.newFixedThreadPool(10));
response.get();//wait for API response
System.out.println("END OF PROGRAM");
}
Output:
200
pool-1-thread-1
END OF PROGRAM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.