Copy Code code as follows:
public class Testcyclicbarrier {
private static final int thread_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 ("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 ();
}
}
}
/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
Cyclicbarrier cb = new Cyclicbarrier (Thread_num, New Runnable () {
Executes when all threads arrive at barrier
@Override
public void Run () {
TODO auto-generated Method Stub
System.out.println ("Inside Barrier");
}
});
for (int i=0;i<thread_num;i++) {
New Thread (New Workerthread (CB)). Start ();
}
}
}
/*
Here is the output:
Worker ' s waiting
Worker ' s waiting
Worker ' s waiting
Worker ' s waiting
Worker ' s waiting
Inside Barrier
Id:12 Working
Id:8 Working
Id:11 Working
Id:9 Working
Id:10 Working
*/
1. Cyclicbarrier a number when initialized, and then calculates the number of threads that called cyclicbarrier.await () into the wait. When the number of threads reaches this amount, all threads that enter the wait state are awakened and continue.
2. Cyclicbarrier, like the meaning of its name, can be seen as an obstacle, and all threads must come together to pass through this barrier.
3. The cyclicbarrier can also be initialized with a runnable parameter, which is executed before all other threads are awakened, after the number of Cyclicbarrier is reached.