Import Java.util.concurrent.cyclicbarrier;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Cyclicbarriertest {public static void main (string[] args) {Executorservice Service = Executors.newcachedthreadpool (); Final Cyclicbarrier cb = new Cyclicbarrier (3); for (int i=0;i<3;i++) {Runnable Runnable = new Runnable () {public void run () {try {Thread.Sleep ((long) (Math.random () *10 000)); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "upcoming meeting place 1, currently available" + (cb.getnumberwaiting () +1) + "One has arrived," + ( Cb.getnumberwaiting () ==2? " All of them, keep going ":" Waiting "); Cb.await (); Thread.Sleep ((Long) (Math.random () *10000)); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "upcoming meeting place 2, currently available" + (cb.getnumberwaiting () +1) + "One has arrived," + ( Cb.getnumberwaiting () ==2? " All of them, keep going ":" Waiting "); Cb.await (); Thread.Sleep ((Long) (Math.random () *10000)); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "upcoming meeting place 3, currently available" + (cb.getnumberwaiting () + 1) + "One has arrived," + ( CB.getnumberwaiting () ==2? " All of them, keep going ":" Waiting "); Cb.await (); } catch (Exception e) {e.printstacktrace ();}} }; Service.execute (runnable); } service.shutdown (); }}
Control only 3 threads are finished at the same time before the thread can continue to execute