java - 仅当我在其中一个线程中收到回调时才释放 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
解决方案
这个 CountDownLatch 对我不起作用,也没有任何互斥锁。做这种事情的最好方法是你从服务器接收回调然后你不应该让那个函数返回任何东西。简单的方法是具有回调功能。
推荐阅读
- python - 在语义中引发异常后,是否可以继续使用其他规则进行解析?
- sql - 如何将以下 SQL 语句转换为更新语句
- git - 在自托管 git repo 上使用 git pull 请求的工作流程
- javascript - 窗口未定义,Vue 平滑滚动 - Nuxt.js
- firefox - Createjs 和 Firefox 72
- python - 是否有一种有效的方法来测试 .onion 链接是否有效
- python - MongoDB 不尊重上限集合的最大值
- android - Renderscript 如何从 2d 浮点数组初始化缓冲区以进行分配
- excel - Excel Tick Marks 改变数据显示
- jquery - 如何使用 jQuery 动态创建包含数据列表的 HTML 输入?