简体   繁体   English

CompletableFuture thenAccept 不起作用

[英]CompletableFuture thenAccept does not work

Welcome, I am so confused why this part of code 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");
}

} }

And the result is:结果是:

END OF PROGRAM

If i have provided ExecutorService JVM should wait for CompletableFuture was completed (.thenAceptAsync section) but the program was finishing immediately.如果我提供了 ExecutorService JVM 应该等待 CompletableFuture 完成(.thenAceptAsync 部分)但程序立即完成。

Probably my mindset is wrong.大概是我的心态错了。 Could somebody explain me this?有人可以解释一下吗?

The program exits before the request is completed.程序在请求完成之前退出。 The request is executed asynchronously using sendAsync and therefore it does not block the execution of the program.该请求使用sendAsync异步执行,因此它不会阻止程序的执行。

To block the execution and wait for the API response, you must use response.get();要阻止执行并等待 API 响应,您必须使用response.get(); as follows:如下:

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: Output:

200
pool-1-thread-1
END OF PROGRAM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM