Java API Tutorial - Java CountDownLatch(int count) Constructor








Syntax

CountDownLatch(int count) constructor from CountDownLatch has the following syntax.

public CountDownLatch(int count)

Example

In the following code shows how to use CountDownLatch.CountDownLatch(int count) constructor.

//  w  w w .j av  a  2s . c  om

import java.util.concurrent.CountDownLatch;
   
public class Main {
  public static void main(String args[]) {
    CountDownLatch cdl = new CountDownLatch(5);
    new MyThread(cdl);
   
    try {
      cdl.await();
    } catch (InterruptedException exc) {
      System.out.println(exc);
    }
    System.out.println("Done");
  }
}
   
class MyThread implements Runnable {
  CountDownLatch latch;
   
  MyThread(CountDownLatch c) {
    latch = c;
    new Thread(this).start();
  }
   
  public void run() {
    for(int i = 0; i<5; i++) {
      System.out.println(i);
      latch.countDown(); // decrement count
    }
  }
}

The code above generates the following result.