CountDownLatch和CyclicBarrier的真实生活示例 [英] Real Life Examples For CountDownLatch and CyclicBarrier

查看:139
本文介绍了CountDownLatch和CyclicBarrier的真实生活示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的一位培训师在解释CountDownLatch和CyclicBarrier之间的差异时给出了一个例子。

One example is given by one of our trainers when he was explaining difference between CountDownLatch and CyclicBarrier.

CountDownLatch :假设一块石头可以被10人抬起,所以你将等待所有10个人来。然后只有你可以抬起石头。

CountDownLatch: Suppose a stone can be lifted by 10 people so you will wait for all 10 to come. Then only you can lift the stone.

CyclicBarrier :如果你要去野餐,你需要先在某个共同点见面,然后你们就会开始你的旅程。

CyclicBarrier: If you are going to a picnic, and you need to first meet at some common point from where you all will start your journey.

如果有人同意这些意见,请给我一些细节。

If Anybody agrees with these comments please give me some details.

我已经阅读了这两个类的sun API。但我需要更多的解释。

I have already read the sun API for both these classes. But I need some more explaination.

推荐答案

关键区别在于 CountDownLatch 将线程分为服务员和到达者,而所有线程使用 CyclicBarrier 执行两种角色。

The key difference is that CountDownLatch separates threads into waiters and arrivers while all threads using a CyclicBarrier perform both roles.


  • 使用一个锁存器,服务员等待最后到达的线程到达,但那些到达的线程不会自行等待。

  • 有了屏障,所有线程都会到达然后等待最后一次到达。

你的闩锁示例暗示所有十个人都必须等待一起抬起石头。不是这种情况。一个更好的现实世界的例子是一个考试提示者,耐心地等待每个学生交出他们的考试。学生一旦完成考试就可以等待,并且可以自由离开。一旦最后一个学生参加考试(或时间限制到期),提示者就会停止等待并离开考试。

Your latch example implies that all ten people must wait to lift the stone together. This is not the case. A better real world example would be an exam prompter who waits patiently for each student to hand in their test. Students don't wait once they complete their exams and are free to leave. Once the last student hands in the exam (or the time limit expires), the prompter stops waiting and leaves with the tests.

这篇关于CountDownLatch和CyclicBarrier的真实生活示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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