Java CountDownLatch class

Introduction

A CountDownLatch is created with the number of events that must occur before the latch is released.

Each time an event happens, the count is decremented.

When the count reaches zero, the latch opens.

CountDownLatch has the following constructor:

CountDownLatch(int num) 

Here, num specifies the number of events that must occur in order for the latch to open.

To wait on the latch, a thread calls await(), which has the forms shown here:

   void await() throws InterruptedException  
boolean await(long wait, TimeUnit tu) throws InterruptedException 

To signal an event, call the countDown() method:

void countDown() 

The following program demonstrates CountDownLatch and creates a latch that requires five events to occur before it opens.

// An example of CountDownLatch. 

import java.util.concurrent.CountDownLatch;

public class Main {
  public static void main(String args[]) {
    CountDownLatch cdl = new CountDownLatch(5);

    System.out.println("Starting");

    new MyThread(cdl);

    try {/*w  ww  .  java 2 s  .c  o  m*/
      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
    }
  }
}



PreviousNext

Related