gpt4 book ai didi

java - 等待 CompletableFuture 完成,然后返回不同的值?

转载 作者:行者123 更新时间:2023-12-02 10:28:27 36 4
gpt4 key购买 nike

我有一个CompletableFuture<Void>它调用一个异步方法,其返回类型我无法更改,或与之相关的任何内容。

我想等待这个方法完成(我手动完成它),然后返回一个String值,我该怎么做?

public String getServer(Player p) {
FutureServer f = new FutureServer(CompletableFuture.runAsync(() -> {
sendUTF(p, "GetServer");
try {
Thread.sleep(10000); //so the future doesnt complete itself
} catch (Exception e) {
e.printStackTrace();
}
}), p.getUniqueId().toString());
serverSet.add(f);
String server = "";

//server isn't final so I can't use it in the lambda
f.getFutureVoid().whenComplete(v -> server = f.getServer());

return server;
}

public class FutureServer {

private CompletableFuture<Void> futureVoid;
private String s;
private String uuid;

public FutureServer(CompletableFuture<Void> futureVoid, String uuid) {
this.futureVoid = futureVoid;
this.uuid = uuid;
}

public String getUuid() {
return uuid;
}

public CompletableFuture<Void> getFutureVoid() {
return futureVoid;
}

public boolean hasServer() {
return s != null;
}

public void setServer(String s) {
this.s = s;
}

public String getServer() {
return s;
}
}

我想将字符串设置为等于 FutureServer#getServer() (自己的方法),但我需要等到CompletableFuture<Void>完成了。我该怎么办?

这是被称为异步且不可更改的方法...我使用的异步调用此其他方法的方法是 sendUTF() .

@Override
public void onPluginMessageReceived(String s, Player p, byte[] bytes) {
if (!s.equals("BungeeCord")) return;

ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
String subChannel = in.readUTF();

switch(subChannel) {
case "GetServer":
String server = in.readUTF();
serverSet.stream().filter(f -> f.getUuid().equals(p.getUniqueId().toString())).findFirst().ifPresent(f -> {
f.setServer(server); //getting the string I need and placing it into this object
f.getFutureVoid().complete(null); //completing the void future manually
});
break;
}

}

最佳答案

你可以这样做:

final AtomicReference<String> server = new AtomicReference<>("");

f.getFutureVoid().whenComplete(v -> server.set(f.getServer())).get(/* maybe add a timeout */);

return server.get();

关于java - 等待 CompletableFuture 完成,然后返回不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53753692/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com