Java 为什么thenApply和thenApplySync不能在完成阶段工作
首先,很明显,我不理解Java 为什么thenApply和thenApplySync不能在完成阶段工作,java,asynchronous,completable-future,completion-stage,Java,Asynchronous,Completable Future,Completion Stage,首先,很明显,我不理解然后再应用,这就是为什么我会出现一个编译器错误,但我尝试过搜索,但没有成功 以下是我的简单代码: import java.util.concurrent.CompletionStage; public class Main5 { public static void main(String[] args) { } static class Game { public void doIt(int id) {
然后再应用,这就是为什么我会出现一个编译器错误,但我尝试过搜索,但没有成功
以下是我的简单代码:
import java.util.concurrent.CompletionStage;
public class Main5 {
public static void main(String[] args) {
}
static class Game {
public void doIt(int id) {
CompletionStage<Player> player = getPlayer(id).thenApplyAsync(p -> {
modifyPlayer(p.getId());
return getPlayer(p.getId());
});
}
private CompletionStage<Player> getPlayer(int id) {
//do http request to get the player info
}
private CompletionStage<Void> modifyPlayer(int id) {
//do http request to modify player's info
}
}
}
getPlayer
方法已经返回了一个完成阶段,那么这有什么错呢
我知道如果我这样做:返回getPlayer(p.getId()).toCompletableFuture().get()代码>它会工作,但我不明白为什么。在我看来,我应该回到完成阶段,而不是对象
非常感谢您的帮助。您应该使用thencomposesync
。您应该从theapplyasync中返回播放机。如果从ApplyAsync返回CompletionStage,那么它是另一个需要执行的可完成任务,这就是为什么要修复它,必须对其调用get()。如果要合并多个可完成的任务,则可以选中此链接:
incompatible types: inference variable U has incompatible bounds
equality constraints: com.testapp.Player
lower bounds: java.util.concurrent.CompletionStage<com.testapp.Player>