This article is a summary of the study of the article on the network, thank you for your selfless sharing.
The Cyclicbarrier class has an integer initial value that represents the number of threads that will be synchronized at the same point. When one of the threads reaches the OK point, it calls the await () method to wait for the other thread. When the thread calls this method, Cyclicbarrier blocks the thread into hibernation until other threads arrive. When the last thread calls the await () method of the Cyclicbarrier class, it wakes up all the waiting threads and continues to perform their tasks.
Note Compare Countdownlatch and Cyclicbarrier:
The role of 1.CountDownLatch is to allow 1 or n threads to wait for other threads to complete execution, while Cyclicbarrier allows n threads to wait for each other.
The counter of the 2.CountDownLatch cannot be reset, and the Cyclicbarrier counter can be reset and used, so it is called the barrier of the loop.
Package Chapter3;import Java.util.concurrent.cyclicbarrier;public class Testcyclicbarrier {private static final int TH Read_num = 5; public static class Workerthread implements runnable{Cyclicbarrier barrier; Public Workerthread (Cyclicbarrier b) {this.barrier = b; } @Override public void Run () {//TODO auto-generated method stub try{ System.out.println ("ID:" +thread.currentthread (). GetId () + "Worker ' s Waiting"); The thread waits here until all the threads have reached barrier. Barrier.await (); System.out.println ("ID:" +thread.currentthread (). GetId () + "working"); }catch (Exception e) {e.printstacktrace (); }}}/** * * <p> * </p> * @author Zhangjunshuai * @date 2014-9- 29 am 11:27:36 * @param args */public static void main (string[] args) {//TODO auto-generated metHod stub cyclicbarrier cb = New Cyclicbarrier (Thread_num, New Runnable () {//execute when all threads reach barrier @Override public void Run () {//TODO auto-generated method stub System.out.pri Ntln ("Inside Barrier"); } }); for (int i=0;i<thread_num;i++) {new THREAD (new Workerthread (CB)). Start (); } }}
Java Concurrency Learning 18--The Thread synchronization tool Cyclicbarrier