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!
A CyclicBarrier can be reused because it will release waiting threads each time the
specified number of threads calls await( ). For example, if you change main( ) 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");
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home