CodesJava

Easy learning with example program codes

countdownlatch in java

The java.util.concurrent.CountDownLatch class allows a thread to wait for other threads to complete. It is used in the situations when one service is only starts when all other required services have started.

Constructor:

public CountDownLatch(int count)

Here count represents the number of threads, for which latch should wait.  It can only be set once and we cannot modify it. All these threads required to do count down by calling CountDownLatch.countDown() when they are completed or ready to perform the job.

Example

import java.util.concurrent.CountDownLatch;
 
public class CountDownLatchTest {
    public static void main(String args[]) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);
        Employee first = new Employee(500, latch, "Employee-1");
        Employee second = new Employee(1000, latch, "Employee-2");
        Employee third = new Employee(1500, latch, "Employee-3");
 
        first.start();
        second.start();
        third.start();
 
        latch.await();
        System.out.println(Thread.currentThread().getName() + " has finished");
    }
}
 
class Employee extends Thread {
    private int delay;
    private CountDownLatch latch;
 
    public Employee(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 ex) {
        	ex.printStackTrace();
        }
    }
}

Output

Employee-1 finished
Employee-2 finished
Employee-3 finished
main has finished
Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status