Fence Cyclicbarrier are similar to latching countdownlatch, which can be said to be counted, to block a group of threads from knowing that an event occurred. The difference is that latching is used to wait for events, while fences are used to wait for other threads.
In one of the previous implementations of countdownlatch--latching, it was mentioned in Countdownlatch that there is a counter in which a thread completes a task and calls the countdown method to make its counter-1, and the waiting thread calls the await method before executing the method. The blocking wait thread will be released when the Countdownlatch counter is reduced to 0 o'clock. So what does cyclicbarrier mean by waiting for other threads?
We simulate a task thread:
1 PackageCyclicbarrier;2 3 Importjava.util.concurrent.BrokenBarrierException;4 ImportJava.util.concurrent.CyclicBarrier;5 6 /**7 * Created by Yulinfeng on 12/19/16.8 */9 Public classTaskImplementsRunnable {Ten Private Finalcyclicbarrier Cyclicbarrier; One A PublicTask (Cyclicbarrier cyclicbarrier) { - This. Cyclicbarrier =Cyclicbarrier; - } the - @Override - Public voidrun () { - Try { +System.out.println (Thread.CurrentThread (). GetId () + "Waiting"); -Cyclicbarrier.await ();//the thread will block when it arrives and will open the fence only when all the threads have arrived. +System.out.println (Thread.CurrentThread (). GetId () + "working"); A}Catch(interruptedexception e) { at e.printstacktrace (); -}Catch(brokenbarrierexception e) { - e.printstacktrace (); - } - } -}
Then we look at the test code and use the thread pool to open 5 threads:
1 PackageCyclicbarrier;2 3 ImportJava.util.concurrent.CyclicBarrier;4 ImportJava.util.concurrent.ExecutorService;5 Importjava.util.concurrent.Executors;6 7 /**8 * Created by Yulinfeng on 12/19/16.9 */Ten Public classTest { One A Public Static voidMain (string[] args) { -Cyclicbarrier Cyclicbarrier =NewCyclicbarrier (5,NewRunnable () { - //execute this thread when all threads arrive the @Override - Public voidrun () { -System.out.println ("Execute barrier"); - } + }); - +Executorservice exec =Executors.newcachedthreadpool (); A for(inti = 0; I < 5; i++){ atExec.execute (NewTask (Cyclicbarrier)); - } - } -}
Execution Result:
Fence--cyclicbarrier