Import java. util. concurrent. brokenBarrierException; import java. util. concurrent. cyclicBarrier; public class javasicbarriertest {public static void main (String [] args) {// create the javasicbarrier object, // and set the concurrent tasks for executing a group of five threads, execute the MainTask task CyclicBarrier cb = new CyclicBarrier (5, new MainTask (); new SubTask ("A", cb ). start (); new SubTask ("B", cb ). start (); new SubTask ("C", cb ). start (); new SubTask ("D", cb ). start (); new SubTask ("E", cb ). start () ;}/ *** last executed task */class MainTask implements Runnable {public void run () {System. out. println ("...... finally, we have to execute the final task ...... ") ;}}/*** a set of concurrent tasks */class SubTask extends Thread {private String name; private CyclicBarrier cb; SubTask (String name, CyclicBarrier cb) {this. name = name; this. cb = cb;} public void run () {System. out. println ("[concurrent task" + name + "] Start execution"); for (int I = 0; I <999999; I ++ ); // simulate the time-consuming task System. out. println ("[concurrent task" + name + "] After execution is completed, the notification barrier"); try {// notify the barrier cb every time a task is executed. await ();} catch (InterruptedException e) {e. printStackTrace ();} catch (BrokenBarrierException e) {e. printStackTrace ();}}}
The result of an execution is as follows:
[Concurrent Task B] Start execution
[Concurrent task D] Start execution
[Concurrent task E] Start execution
[Concurrent task A] Notification barrier after execution is completed
[Concurrent task E] Notification barrier after execution is completed
[Concurrent task D] Notification barrier after execution is completed
[Concurrent task C] Start execution
[Concurrent Task B] Notification barrier after execution is completed
[Concurrent task C] Notification barrier after execution is completed
... The final task is finally to be executed ......