首页 > 解决方案 > 仅当我在其中一个线程中收到回调时才释放 CountDownLatch

问题描述

doneSignal.await()在这种情况下何时调用?我的要求是等待回电,直到收到回调。我尝试在其他线程和主线程中调用它。但运气不好,从未收到回调,因此冻结了应用程序,最初当我不使用 CountDownLatch 时,getCall 立即返回空值,而无需等待回调。下面是我的代码

public UserSubscriptions getDocument(final String uid) {
        final UserSubscriptions[] userSubscriptions = new UserSubscriptions[1];
        final CountDownLatch doneSignal = new CountDownLatch(1);
        try {
            Thread getCall = new Thread(new Runnable() {
                @Override
                public void run() {
                 try{
                    DocumentReference docRef = db.collection("xyz").document(uid);
                    docRef.get()
                            .addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    userSubscriptions[0] = null;
                                    TimerLog.e("document retrieve failed");
                                    doneSignal.countDown();
                                }
                            })
                            .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                                @Override
                                public void onSuccess(DocumentSnapshot documentSnapshot) {
                                    userSubscriptions[0] = documentSnapshot.toObject(UserSubscriptions.class);
                                    TimerLog.e("document retrieved successfully " + userSubscriptions[0].toString());
                                    doneSignal.countDown();
                                }
                            });
                    TimerLog.e("control exitted from run");
                } finally {
                        TimerLog.e("Nads in finally");
                    }
                }
            });
            getCall.start();
            TimerLog.e("before");
            doneSignal.await();
            TimerLog.e("after");
        } catch (InterruptedException e) {
            TimerLog.e("exception in await "+e.getLocalizedMessage());
        }
        return userSubscriptions[0];
    }

控制台输出:

before
control exitted from run
in finally

标签: javaandroidmultithreading

解决方案


这个 CountDownLatch 对我不起作用,也没有任何互斥锁。做这种事情的最好方法是你从服务器接收回调然后你不应该让那个函数返回任何东西。简单的方法是具有回调功能。


推荐阅读