Real Life Examples For CountDownLatch and CyclicBarrier

前端 未结 11 1329
余生分开走
余生分开走 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:28

    CountDownLatch: "The Best Real Life Example is - Race"

    (Any Type of Race for Example: Horse Race or Bike Race or Car Race etc.,)

    The Horse Race is also one of the Best Real Life Example can implement using CountDownLatch.

    1. The Race Distance will be Announce or Fixed. (Race Distance in Km/Miles/Yards)
    2. Number of Horses will be participating in Race. (Horses Count)
    3. Before starting Race all horses will arrive at starting gate or starting point.
    4. Once all horses reached at starting gate/starting point then only Race will start.
    5. Once signaled - All horse will start at once / releases them all at once.
    6. All horses will start running... to finish Race Distance / to reach finishing point.
    7. Once all horses completed the Race Distance or Reaches finishing point.
    8. We get all horses position / places List - Winners List.
    9. Announce the Winner of the Race

    We use Two CountDownLatch for Start and finish the Race.

    CountDownLatch start  = new CountDownLatch(1); // Start signal - will be always 1 only once All Horses Reach at Starting Point signal for START RACE.
    
    CountDownLatch finish = new CountDownLatch(horses_Count); // Number of horses participating in Race nothing but Threads/Horses Count.
    

    Horses - is nothing but Threads.

    start.await() : Each Horse/Thread once Reach at starting gate/starting point it will wait for other horses/Threads to reach at starting gate/starting point is nothing but - start.await();

    start.countDown() : Once all horses/Threads reached at starting gate/starting point we signal to start Race is nothing but - start.countDown(); When start.countDown(); is called it will notifyAll() to All waiting Horses/Threads to Start Race.

    finish.await() : Once all horses/Threads started Race the Main Thread will be wait to finish or complete by All horses/Threads is nothing but - finish.await();

    finish.countDown(): Once each horse/Thread finish Race It will be reduce the count once last horse/Thread reduce count to ZERO then Race Completed/Finished finish.countDown(); When finish.countDown(); is called when count became to ZERO it will notify() to waiting Main Thread - All Horses/Threads Finished/Completed the RACE.

提交回复
热议问题