【问题标题】:CompletableFuture thenAccept does not workCompletableFuture thenAccept 不起作用
【发布时间】:2022-01-02 17:00:22
【问题描述】:

欢迎, 我很困惑为什么这部分代码不起作用。

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 部分)但程序立即完成。

可能我的心态是错误的。有人可以解释一下吗?

【问题讨论】:

  • 您无需等待请求完成;你的程序刚刚退出。
  • 我应该如何使它正确?
  • 所以我必须将它加入 MainThread。我之前感谢JVM只要存在任何线程就可以工作。我错了非常感谢
  • sendAsync没有指定执行者;所以使用公共池。我认为您的代码不会使用您的自定义执行器。

标签: java multithreading asynchronous


【解决方案1】:

程序在请求完成之前退出。该请求使用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");
}

输出:

200
pool-1-thread-1
END OF PROGRAM

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 2021-04-16
    • 1970-01-01
    • 2023-03-31
    • 2020-03-17
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    相关资源
    最近更新 更多