有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程如何在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) 个答案

  1. # 1 楼答案

    匿名类中使用的变量必须是有效的最终变量
    这意味着您不能将它们分配给其他对象,但您可以对它们调用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;
            }
        }
    
    }