在 java 中使用 CompletableFuture 时遇到问题。我有 2 个选择请求,它们是在从服务器接收响应时填充的。
在连接线程(THREAD-1)(使用反应器)中,我使用:
if(hasException) {
selectFuture.completeExceptionally(new ClientException(errorCode));
} else {
System.out.println("Before complete future");
selectFuture.complete(result);
System.out.println("After complete future");
}
Run Code Online (Sandbox Code Playgroud)
在其他线程(THREAD-2)中,我使用:
CompleteFuture.allOf(allSelect).whenComplete((aVoid, throwable) -> {
System.out.println("Receive all future");
// Do sth here
});
Run Code Online (Sandbox Code Playgroud)
我的情况是系统打印出“接收所有未来”但调用时 THREAD-1 被阻止future.complete(result);它无法退出该命令。如果在 THREAD-2 中,我使用CompletableFuture.allOf(allOfSelect).get(),THREAD-1 将正确运行。但是使用CompletableFuture.get()会降低性能,所以我想使用CompletableFuture.whenComplete().
谁能帮我解释一下阻塞的原因?
谢谢!