798 Part II: The Java Library
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);
}
}
}
// An object of this class is called when the
// CyclicBarrier ends.
class BarAction implements Runnable {
public void run() {
System.out.println("Barrier Reached!");
}
}
The output is shown here. (The precise order in which the threads execute may vary.)
Starting
A
B
C
Barrier Reached!
ACyclicBarriercan be reused because it will release waiting threads each time the
specified number of threads callsawait( ). For example, if you changemain( )in the preceding
program so that it looks like this:
public static void main(String args[]) {
CyclicBarrier cb = new CyclicBarrier(3, new BarAction() );
System.out.println("Starting");
new MyThread(cb, "A");
new MyThread(cb, "B");
new MyThread(cb, "C");