最近,我正在学习RxJava
。我们都知道CountDownLatch
在计算到zero
时会停止。好吧,但是当我运行下面的代码时,CountDownLaych
永远不会停止!我尝试运行与Java项目相同的代码,可以停止!
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CountDownLatch latch = new CountDownLatch(5);
Observable
.interval(1, TimeUnit.SECONDS)
.subscribe(new Action1<Long>() {
@Override
public void call(Long counter) {
latch.countDown();
long count = latch.getCount();
Log.d(TAG, "call get -> " + counter + ", latch count -> " + count);
}
});
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
在Android Studio中,这些代码的输出方式如下:
D/MainActivity: call get -> 0, latch count -> 4
D/MainActivity: call get -> 1, latch count -> 3
D/MainActivity: call get -> 2, latch count -> 2
D/MainActivity: call get -> 3, latch count -> 1
D/MainActivity: call get -> 4, latch count -> 0
D/MainActivity: call get -> 5, latch count -> 0
D/MainActivity: call get -> 6, latch count -> 0
D/MainActivity: call get -> 7, latch count -> 0
....
答案 0 :(得分:4)
根据the documentation,闩锁不会停止计数为零。代替:
如果当前计数等于零,则没有任何反应。
尝试修改try
块,使其如下所示:
Log.d(TAG, "call await");
latch.await();
Log.d(TAG, "released");
我相信你会看到当你的闩锁达到零时线程被释放。如果你希望你的观察者在发生这种情况时停止发射,那么你将不得不取消订阅。