Copy the 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");
//Threads wait here until all threads reach the 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() {
//Executed when all threads reach the 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. Specify a number when CyclicBarrier is initialized, and then calculate the number of threads that call CyclicBarrier.await() to wait. When the number of threads reaches this number, all threads that have entered the waiting state are awakened and continue.
2. CyclicBarrier, as its name implies, can be regarded as an obstacle. All threads must be present before they can pass this obstacle together.
3. CyclicBarrier can also take a Runnable parameter initially. This Runnable task will be executed after the number of CyclicBarriers is reached and before all other threads are awakened.