- when a set of two or more threads must wait at a predetermined point of execution until all threads in the set have reached that point, CyclicBarrier is used.
- it allows you to define a synchronization object that suspends until the specified number of threads has reached the barrier point.
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
class Task implements Runnable {
CyclicBarrier cb;
Task(CyclicBarrier cb){
this.cb = cb;
}
/**
* Runs this operation.
*/
@Override
public void run() {
String name = Thread.currentThread().getName();
try {
System.out.println(name + " reached the barrier point");
cb.await();
} catch (InterruptedException | BrokenBarrierException ex) {
System.out.println(ex.getMessage());
}
}
}
public class Main {
public static void main(String[] args) {
// calls the lambda on 2 set of 3 threads, since we have 6 threads in the code
CyclicBarrier cb = new CyclicBarrier(3, ()-> System.out.println("Barrier Reached"));
new Thread(new Task(cb),"thread1").start();
new Thread(new Task(cb),"thread2").start();
new Thread(new Task(cb),"thread3").start();
new Thread(new Task(cb),"thread4").start();
new Thread(new Task(cb),"thread5").start();
new Thread(new Task(cb),"thread6").start();
}
}