Java Thread How to - Compare Countdown latch vs Cyclic barrier








Question

We would like to know how to compare Countdown latch vs Cyclic barrier.

Answer

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
// w  w  w  .ja  v a  2s .  co m
public class Main {
  static CyclicBarrier barrier = new CyclicBarrier(3);
  public static void main(String[] args) throws InterruptedException {
    new Worker().start();
    Thread.sleep(1000);
    new Worker().start();
    Thread.sleep(1000);
    new Worker().start();
    Thread.sleep(1000);

    System.out.println("Barrier automatically resets.");

    new Worker().start();
    Thread.sleep(1000);
    new Worker().start();
    Thread.sleep(1000);
    new Worker().start();
  }
}

class Worker extends Thread {
  @Override
  public void run() {
    try {
      Main.barrier.await();
      System.out.println("Let's play.");
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (BrokenBarrierException e) {
      e.printStackTrace();
    }
  }
}

The code above generates the following result.