多线程如何在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回调中编辑可验证的值,我怎么能绕过它呢。我想返回一个布尔值,并希望调用线程等待,直到我从数据库得到响应
# 1 楼答案
匿名类中使用的变量必须是有效的最终变量
这意味着您不能将它们分配给其他对象,但您可以对它们调用setter
所以,你可以这样做: