CountDownLatch vs. Semaphore

后端 未结 6 1135
不知归路
不知归路 2020-11-28 01:30

Is there any advantage of using

java.util.concurrent.CountdownLatch

instead of

java.util.concurrent.Semaphore?

As far as I can tell the fol

6条回答
  •  [愿得一人]
    2020-11-28 02:05

    Say you walked in to golf pro shop, hoping to find a foursome,

    When you stand in line to get a tee time from one of the pro shop attendants, essentially you called proshopVendorSemaphore.acquire(), once you get a tee time, you called proshopVendorSemaphore.release().Note: any of the free attendants can service you, i.e. shared resource.

    Now you walk up to starter, he starts a CountDownLatch(4) and calls await() to wait for others, for your part you called checked-in i.e. CountDownLatch.countDown() and so does rest of the foursome. When all arrive, starter gives go ahead(await() call returns)

    Now, after nine holes when each of you take a break, hypothetically lets involve starter again, he uses a 'new' CountDownLatch(4) to tee off Hole 10, same wait/sync as Hole 1.

    However, if the starter used a CyclicBarrier to begin with, he could have reset the same instance in Hole 10 instead of a second latch, which use & throw.

提交回复
热议问题