Java CountDownLatch wait for multiple concurrent events

Introduction

The Java concurrency API CountDownLatch class allows one or more threads to wait until a set of operations are made.

This class is initialized with an integer number.

The number is the number of operations the threads are going to wait for.

When a thread wants to wait for these operations, it uses the await() method.

The wait() method puts the thread to sleep until the operations are completed.

When one of these operations finishes, it uses the countDown() method to decrement the internal counter of the CountDownLatch class.

When the counter arrives to 0, the class wakes up all the threads that were sleeping in the await() method.

import java.util.concurrent.TimeUnit;
import java.util.concurrent.CountDownLatch;
public class Main {
  public static void main(String[] args) {
    // Creates a Room with 10 users.
    ClassRoom conference=new ClassRoom(10);
    // Creates a thread to run the Room and start it.
    Thread threadConference=new Thread(conference);
    threadConference.start();/*  ww w .  ja  v  a2  s  .  c o  m*/
    
    // Creates ten users, a thread for each one and starts them
    for (int i=0; i<10; i++){
      Student p=new Student(conference, "user "+i);
      Thread t=new Thread(p);
      t.start();
    }
  }
}

class Student implements Runnable {
  private ClassRoom classRoom;
  private String name;

  public Student(ClassRoom c, String name) {
    this.classRoom=c;
    this.name=name;
  }

  @Override
  public void run() {
    Long duration=(long)(Math.random()*10);
    try {
      TimeUnit.SECONDS.sleep(duration);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } 
    classRoom.arrive(name);
  }
}
class ClassRoom implements Runnable{
  private final CountDownLatch controller;

  public ClassRoom(int number) {
    controller=new CountDownLatch(number);
  }

  public void arrive(String name){
    System.out.printf("%s has arrived.\n",name);
    // This method uses the countDown method to decrement the internal counter of the
    // CountDownLatch
    controller.countDown();
    System.out.printf("Waiting for %d users.\n",controller.getCount());
  }
  
  /**
   * Controller of the Room. It waits for all
   * the users and the, starts the conference
   */
  @Override
  public void run() {
    System.out.printf("Initialization: %d users.\n",controller.getCount());
    try {
      // Wait for all the users
      controller.await();
      // Starts the conference
      System.out.printf("Let's start...\n");
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }  
}



PreviousNext

Related