1:cyclicbarrier class Description
A synchronization helper class that allows a set of threads to wait for each other until a common barrier point (common barrier points) is reached. In programs that involve a set of fixed-size threads, these threads have to wait for each other, and cyclicbarrier is useful at this time. Because the barrier can be reused after releasing the waiting thread, it is called a cyclic barrier
2: Usage Scenarios
When all subtasks are completed, the main task is executed, and you can choose to use Cyclicbarrier
3: View API
Now write a demo play,
Package Cn.kge.com.thread;import Java.io.ioexception;import Java.util.random;import Java.util.concurrent.brokenbarrierexception;import Java.util.concurrent.cyclicbarrier;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class CyclicBarrierTest {public static void Main (string[] args) throws IOException, Interruptedexception {//If the parameter is changed to 4, but only 3 players are added below, this will wait forever Waits until all parties has invoked await on this barrier. Cyclicbarrier barrier = new Cyclicbarrier (4); Executorservice executor = Executors.newfixedthreadpool (4); Executor.submit (New Thread (New Runner (barrier, "Zhang San")); Executor.submit (New Thread (New Runner (barrier, "John Doe")); Executor.submit (New Thread (New Runner (barrier, "Harry")); Executor.submit (New Thread (New Runner (barrier, "Lao Liu")); Executor.shutdown (); }} class Runner implements Runnable {//A synchronization helper class that allows a set of threads to wait until a common barrier point is reached (Common BArrier point) private cyclicbarrier barrier; private String name; Public Runner (cyclicbarrier barrier, String name) {super (); This.barrier = barrier; THIS.name = name; @Override public void Run () {try {thread.sleep (New Random ()). Nextint (8)); SYSTEM.OUT.PRINTLN (name + "immediate to ..."); Barrier's await method waits until all the participants have already raised the await method in this barrier. Barrier.await (); } catch (Interruptedexception e) {e.printstacktrace (); } catch (Brokenbarrierexception e) {e.printstacktrace (); } System.out.println ("Go to the girls Together"); } }
Cyclicbarrier use of Java