import java.util.concurrent.CyclicBarrier; import java.util.concurrent.BrokenBarrierException; public class CyclicBarrierExample { // Runnable task that will be executed by each thread static class Task implements Runnable { private CyclicBarrier barrier; public Task(CyclicBarrier barrier) { this.barrier = barrier; } @Override public void run() { try { System.out.println(Thread.currentThread().getName() + " is waiting at the barrier."); barrier.await(); System.out.println(Thread.currentThread().getName() + " has crossed the barrier."); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } } public static void main(String[] args) { final int numberOfThreads = 3; CyclicBarrier barrier = new CyclicBarrier(numberOfThreads, new Runnable() { @Override public void run() { // This task will be executed once all threads reach the barrier System.out.println("All threads have reached the barrier, now proceeding further."); } }); for (int i = 0; i < numberOfThreads; i++) { Thread thread = new Thread(new Task(barrier), "Thread " + (i + 1)); thread.start(); } } }