Java javasicbarrier Usage Analysis, javacyclicbarrier
Copy codeThe Code is 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 threads reach 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 (){
// Execute when all threads reach 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 ();
}
}
}
/*
The following 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. Define a number for javasicbarrier initialization, and then calculate the number of threads that call javasicbarrier. await () to enter the waiting state. When the number of threads reaches this value, all threads that enter the waiting state are awakened and continue.
2. javasicbarrier, like its name, can be seen as a barrier. All threads must be completed before they can pass the barrier together.
3. CyclicBarrier can also contain a Runnable parameter at the beginning. After the number of javasicbarrier tasks reaches, all other threads are executed before being awakened.