Usage analysis of CyclicBarrier in Java

  • 2020-04-01 01:37:11
  • OfStack


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 reach the barrier.
                 barrier.await();
                 System.out.println("ID:"+Thread.currentThread().getId()+" Working");
             }catch(Exception e){
                 e.printStackTrace();
             }
         }

     }

     
     public static void main(String[] args) {
         // TODO Auto-generated method stub
         CyclicBarrier cb = new CyclicBarrier(THREAD_NUM, new Runnable() {
             //Execute 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();
         }
     }

 }
 

1. CyclicBarrier initializes by specifying a number, and then counts the number of threads that have called CyclicBarrier. Await () to enter the wait. When this number is reached, all threads entering the wait state are awakened and continue.
As its name suggests, the CyclicBarrier can be seen as a barrier that all threads must get through together.
3. CyclicBarrier can also start with a Runnable parameter, which is executed before all other threads are awakened after the number of CyclicBarrier is reached.


Related articles: