Java CyclicBarrier class

Introduction

To make threads wait at a predetermined execution point, use CyclicBarrier class.

It defines a synchronization object that suspends until the specified number of threads has reached the barrier point.

CyclicBarrier has the following two constructors:

CyclicBarrier(int numThreads)  
CyclicBarrier(int numThreads, Runnable action) 

Here is an example that illustrates CyclicBarrier.

It waits until a set of three threads has reached the barrier.


import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Main {
  public static void main(String args[]) {
    CyclicBarrier cb = new CyclicBarrier(3, ()-> {
      System.out.println("hi");
    });/*from  w  w  w  .  j  a v  a 2s.  c o  m*/

    System.out.println("Starting");

    new MyThread(cb, "A");
    new MyThread(cb, "B");
    new MyThread(cb, "C");

  }
}

// A thread of execution that uses a CyclicBarrier.
class MyThread implements Runnable {
  CyclicBarrier cbar;
  String name;

  MyThread(CyclicBarrier c, String n) {
    cbar = c;
    name = n;
    new Thread(this).start();
  }

  public void run() {

    System.out.println(name);

    try {
      cbar.await();
    } catch (BrokenBarrierException exc) {
      System.out.println(exc);
    } catch (InterruptedException exc) {
      System.out.println(exc);
    }
  }
}



PreviousNext

Related