Java 并发:倒计时闩锁与循环屏障 [英] Java concurrency: Countdown latch vs Cyclic barrier
问题描述
我正在阅读 java.util.concurrent API,发现
CountDownLatch
:一种同步辅助工具,允许一个或多个线程等待其他线程中正在执行的一组操作完成.CyclicBarrier
:一种同步辅助工具,它允许一组线程相互等待,以达到共同的障碍点.
CountDownLatch
: A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.CyclicBarrier
: A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.
对我来说两者似乎是平等的,但我相信还有更多.
To me both seems equal, but I am sure there is much more to it.
例如,在CountdownLatch 中,倒计时值无法重置,这在CyclicBarrier 的情况下可能发生
.
两者之间还有其他区别吗?
有人想要重置倒计时值的用例
是什么?
Is there any other difference between the two?
What are the use cases
where someone would want to reset the value of countdown?
推荐答案
一个主要区别是 CyclicBarrier 接受一个(可选的)Runnable 任务,一旦满足公共障碍条件就会运行该任务.
One major difference is that CyclicBarrier takes an (optional) Runnable task which is run once the common barrier condition is met.
它还允许您获取在屏障处等待的客户端数量以及触发屏障所需的数量.一旦触发,屏障将重置并可再次使用.
It also allows you to get the number of clients waiting at the barrier and the number required to trigger the barrier. Once triggered the barrier is reset and can be used again.
对于简单的用例 - 服务启动等...... CountdownLatch 很好.CyclicBarrier 对于更复杂的协调任务很有用.这种事情的一个例子是并行计算 - 其中多个子任务参与计算 - 有点像 MapReduce.
For simple use cases - services starting etc... a CountdownLatch is fine. A CyclicBarrier is useful for more complex co-ordination tasks. An example of such a thing would be parallel computation - where multiple subtasks are involved in the computation - kind of like MapReduce.
这篇关于Java 并发:倒计时闩锁与循环屏障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!