我有一个方法,我在其中调用另一个具有回调的方法。我想在离开我的方法之前收到这个回调。我看到其他一些使用闩锁的帖子。我的代码如下所示:
public void requestSecurityToken(<some params>){
final CountDownLatch latch = new CountDownLatch(1);
MyFunction.execute(<someParams>, new RequestListener<Login>() {
@Override
public void onRequestFailure(SpiceException spiceException) {
//TODO
}
@Override
public void onRequestSuccess(Login login) {
//handle some other stuff
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
这不行,方法卡在await()函数里了。发生的事情是,该方法立即跳转到 await(),并且不会再次进入 onRequestSuccess() 或 onRequestFailure() 方法。我想这是一个并发问题......关于如何解决这个问题的任何想法?
编辑:添加了我创建闩锁的代码行。
最佳答案
当你这样做的时候
new RequestListener<Login>
您正在将一个对象传递给您的函数,该函数实现了一个接口(interface)。
这就是为什么不调用这些方法的原因,只有当您获得请求结果(成功或失败)时才会调用这些方法。
您可以改为执行此操作。
MyFunction.execute(<someParams>, new RequestListener<Login>() {
@Override
public void onRequestFailure(SpiceException spiceException) {
someFunction();
}
@Override
public void onRequestSuccess(Login login) {
//handle some other stuff
someFunction();
latch.countDown();
}
});
public void someFunction()[
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
关于java - 如何在离开方法之前等待回调(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44242096/