What is CountDownLatch in Java and it’s example

In this tutorial, you will learn the concept of CountDownLatch concept and how to implement it with an example in Java Programming Language.

What is CountDownLatch?

CountDownLatch is used for the synchronization of several tasks or threads. This feature ensures that a new task waits for the ongoing task to complete its process. While creating an object of CountDownLatch, we are required to specify the number of threads/tasks it should wait for before getting started. Once they finish the task they start the countdown and as soon as the count reaches zero, the task that has been waiting for starts running.

Example in Java: CountDownLatch

This code is just an example to show the use of CountDownLatch using four tasks.

package javaapplication17;
import java.util.concurrent.CountDownLatch; 
public class JavaApplication17 {
   public static void main(String args[])  
                   throws InterruptedException 
    { 
       CountDownLatch latch = new CountDownLatch(4); 
       Task first = new Task(500, latch, "Task-1"); 
        Task second = new Task(2000, latch,  
                                  "Task-2"); 
        Task third = new Task(3000, latch,  
                                  "Task-3"); 
        Task fourth = new Task(3400, latch,  
                                  "Task-4"); 
        first.start(); 
        second.start(); 
        third.start(); 
        fourth.start(); 
  
        latch.await(); 
  
        System.out.println(Thread.currentThread().getName() + 
                           " has finished"); 
    } 
} 
class Task extends Thread 
{ 
    private int delay; 
    private CountDownLatch latch; 
  
    public Task(int delay, CountDownLatch latch, 
                                    String name) 
    { 
        super(name); 
        this.delay = delay; 
        this.latch = latch; 
    } 
  
    @Override
    public void run() 
    { 
        try
        { 
            Thread.sleep(delay); 
            latch.countDown(); 
            System.out.println(Thread.currentThread().getName() 
                            + " finished"); 
        } 
        catch (InterruptedException e) 
        { 
            e.printStackTrace(); 
        } 
    } 
} 

Output:

Task-1 finished
Task-2 finished
Task-3 finished
Task-4 finished
main has finished

Also read: pattern() method in Java with examples

Leave a Reply

Your email address will not be published. Required fields are marked *