Java并发:倒计时锁存器与循环障碍 [英] Java concurrency: Countdown latch vs Cyclic barrier

查看:235
本文介绍了Java并发:倒计时锁存器与循环障碍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览 java.util.concurrent API ,并发现




  • CountDownLatch :同步辅助

  • CyclicBarrier :允许一个或多个线程等待其他线程中执行的一组操作完成。所有的线程都等待彼此达到共同的屏障点。



对我来说,两者似乎相等,但我相信还有更多。



例如,在 CoundownLatch中,倒计时值无法重置,这可能发生在CyclicBarrier



两者之间是否还有其他区别?

用例有人想要重置countdown的值?

解决方案

一个主要区别是 CyclicBarrier 接受一个(可选)Runnable任务,一旦满足公共屏障条件就运行。



它还允许您获取在屏障处等待的客户端数量和触发屏障所需的数量。一旦触发,屏障被复位并可以再次使用。



对于简单的用例 - 服务启动等...一个CountdownLatch很好。循环障碍物对于更复杂的协调任务是有用的。这种事情的一个例子是并行计算 - 在计算中涉及多个子任务 - 类似 MapReduce 。 / p>

I was reading through the java.util.concurrent API, and found that

  • 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.

For example, in CoundownLatch, the countdown value could not be reset, that can happen in the case of CyclicBarrier.

Is there any other difference between the two?
What are the use cases where someone would want to reset the value of countdown?

解决方案

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆