3

In Java once a CountdownLatch reaches its state = 0, it cannot change it, so it remains open forever. I wonder why implementors don't allow to reuse CountDownLatch?

4

3 回答 3

5

如果它是可重用的,你将如何处理不同的到达迭代?例如,假设您想在CountDownLatch.

CountDownLatch latch = new CountDownLatch(1);

latch.await();

然后一个线程调用

latch.countDown();

await释放。现在您有另一个线程,只有在之前的线程倒计时时才应该释放。所以你调用latch.await(). 如果闩锁是可变的,线程应该等待还是继续?锁存器怎么知道这个等待不应该是另一个周期(或阶段)?

最后,事实并非如此,这是理所当然的。可变锁存器很困难,但它是可能的。Java 7 推出了Phaser。它将每次下一次迭代视为一个阶段,您可以告诉移相器在特定阶段等待:

phaser.awaitAdvance(phase);

于 2014-12-04T15:18:02.877 回答
1

因为它是 CountDownLatch 特有的功能。如果 CountDownLatch 将重置其计数器,那么它的行为就像 CyclicBarrier

于 2014-12-04T15:12:55.953 回答
0

你可以这样做:

ReusableCountLatch latch = new ReusableCountLatch(); // creates latch with initial count 0
ReusableCountLatch latch2 = new ReusableCountLatch(10); // creates latch with initial count 10

latch.increment(); // increments counter

latch.decrement(); // decrement counter

latch.waitTillZero(); // blocks until counts falls to zero

boolean succeeded = latch.waitTillZero(200, MILLISECONDS); // waits for up to 200 milliseconds until count falls to zero

int count = latch.getCount(); // gets actual count

要使用它,您只需添加一个依赖项:

compile 'com.github.matejtymes:javafixes:1.3.0'
于 2019-06-20T23:20:18.057 回答