Real Life Examples For CountDownLatch and CyclicBarrier

前端 未结 11 1443
余生分开走
余生分开走 2021-01-30 13:52

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

CountDownLatch: Suppose a stone can be lifted by

11条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-30 14:42

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

    • With a latch, the waiters wait for the last arriving thread to arrive, but those arriving threads don't do any waiting themselves.
    • With a barrier, all threads arrive and then wait for the last to arrive.

    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.

提交回复
热议问题