[英]How to sync a async operation in java
我目前正在创建一个数据库util类,但我的mongodb驱动程序是异步的,我现在的问题是如何同步他? 我目前的尝试看起来像这样:
public boolean isBanIDFree(String banid) {
boolean value = false;
Thread thread = Thread.currentThread();
MongoCollection<Document> collection = database.getCollection("Bans");
collection.find(new Document("ID", banid)).first(new SingleResultCallback<Document>() {
@Override
public void onResult(Document result, Throwable t) {
if(result == null) {
value = true;
}
thread.notify();
}
});
try {
thread.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return value;
}
但我无法编辑onResult Callback中的可验证值,我该如何绕过它。 我想返回一个布尔值,并希望调用线程等到我从数据库得到响应
匿名类中使用的变量必须是有效的。
这意味着你不能将它们分配给其他东西,但你可以在它们上面调用一个setter。
所以,你可以这样做:
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
BooleanWrapper b = new BooleanWrapper();
CompletableFuture.runAsync(() -> b.setValue(true));
// ...
}
private static class BooleanWrapper {
private boolean value;
public boolean getValue() {
return value;
}
public void setValue(boolean value) {
this.value = value;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.