Fences are similar to latching, but they are different.
Latching is used to wait for an event, while a fence is used to wait for other threads. What does that mean? The event that the latch is used to wait is the countdown event, and only the thread that is waiting before the countdown event executes can continue; While the fence does not resemble the Countdown event control thread execution, only the thread's await method can control the waiting thread execution.
Cyclicbarrier stressed that n threads, everyone waits, as long as one is not finished, everyone has to wait.
Scene Analysis: 10 people go for a spring outing, the requirement to reach a location to continue to move forward. The code is as follows
ImportJava.util.concurrent.BrokenBarrierException;ImportJava.util.concurrent.cyclicbarrier;class Cyclicbarrierworker implements Runnable {Private intIdPrivateCyclicbarrier barrier; Public Cyclicbarrierworker(intIdFinalCyclicbarrier barrier) { This. id = ID; This. Barrier = barrier; }@Override Public void Run() {//TODO auto-generated method stub Try{System.out.println (id +"th people Wait"); Barrier.await ();//Everyone waits for the last thread to arrive}Catch(Interruptedexception | Brokenbarrierexception e) {//TODO auto-generated catch blockE.printstacktrace (); } }} Public class testcyclicbarrier { Public Static void Main(string[] args) {intnum =Ten; Cyclicbarrier barrier =NewCyclicbarrier (NUM,NewRunnable () {@Override Public void Run() {//TODO auto-generated method stubSystem.out.println ("Go on together!"); } }); for(inti =1; I <= num; i++) {NewThread (NewCyclicbarrierworker (i, Barrier)). Start (); } }}
Output
1 th people wait 2 th people wait 3 th people wait 4 th people wait 5 th people wait 7 th people wait Span class= "hljs-number" >8 th people wait 6 th people wait 9 th people wait 10 th people wait Go on together !
Java Concurrency Programming Fence (cyclicbarrier) detailed