Countdown Latch

  • Eclipse: Oxygen
  • Java: 1.8

This tutorial deals with the countdown latch. The basic use of this is that we can place the thread that we want to execute after a certain number of threads. This can be done by setting the countdown number to the number of threads after which we want the specific thread to be executed.

In the following program, we see the inconsistency in our program where the main thread is not waiting for other thread before it starts.

Here we create a task that is going to wait for four threads before it starts. Then we create four threads and start them. As we can see the inconsistency in our program where main thread is not waiting for other thread before it starts.

Output

I am in main thread

Thread running with thread name Thread-0

Thread execution completed

*************************

Thread running with thread name Thread-2

Thread execution completed

*************************

Thread running with thread name Thread-1

Thread execution completed

*************************

Thread running with thread name Thread-3

Thread execution completed

*************************

The following program demonstrates how to use CountDownLatch, It’s used when a thread needs to wait for other threads before starting its work.

As we have seen above program, where we create a task that is going to wait for four threads before it starts. Then we create four threads and start them.

Here we call the latch.await() method. This method will force the main thread waits for four threads until the lock is released.

In order to release the lock, we use latch.countDown() method. It reduces the count of the latch and released all waiting threads.

Output

Thread running with thread name Thread-0

Thread execution completed

*************************

Thread running with thread name Thread-2

Thread execution completed

*************************

Thread running with thread name Thread-3

Thread execution completed

*************************

Thread running with thread name Thread-1

Thread execution completed

*************************

I am in main thread

Here is the same example which demonstrates if the counter variable is more than 4 and we call latch.countDown() method 4 times. Then we won’t be able to terminate the program and can’t execute the main thread.

Output

Thread running with thread name Thread-0

Thread execution completed

*************************

Thread running with thread name Thread-2

Thread execution completed

*************************

Thread running with thread name Thread-3

Thread execution completed

*************************

Thread running with thread name Thread-1

Thread execution completed

*************************

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu