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