It's a synchronizer, that is an high-level abstraction for thread synchronization.
The threads wait each other until all reach a barrier together, then an optional thread can be run.
It's named "cyclic" because it's reusable and you don't have to create a new instance every time.
It requires a fixed number of threads.
It's not advanceable, that means all threads need to wait for the barrier.
Here's an example:
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * Class to demonstrate the use of CyclicBarrier * @author Davis Fiore */ public class App { /** * This class represent threads that have to wait each other * to reach a barrier. */ static private class Worker implements Runnable { private final CyclicBarrier cb; /** * Constructor that initialize the thread with the global * CyclibBarrier * @param cb CyclicBarrier for the app */ public Worker(final CyclicBarrier cb) { this.cb = cb; } /** * Main thread method that wait until all the * other threads reach the barrier */ @Override public void run() { try { cb.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } } /** * Main method to test a CyclicBarrier * @param args */ public static void main(String[] args) { // Create a CyclicBarrier for three threads CyclicBarrier cb = new CyclicBarrier(3, new Runnable() { /** * Method to be run after the barrier has been reached */ @Override public void run() { System.out.println("Barrier reached!"); } }); // Create three threads Thread thread1 = new Thread(new Worker(cb)); Thread thread2 = new Thread(new Worker(cb)); Thread thread3 = new Thread(new Worker(cb)); // Start the threads thread1.start(); thread2.start(); thread3.start(); } }
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.