Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CyclicBarrier re-use Example

Does CyclicBarrier best suitable, in this case. I want to run n threads parallel in Stages (wait at Stages until all threads completes that Stage).

        public class CyclicBarr {


        public static void main(String[] args) {


            CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() {
                private int count =1;
                @Override
                public void run() {
                    System.out.println("Completed..!! "+(count++));
                }
            });

            for (int i = 1; i <= 3; i++) {

                Thread t = new Thread(new CuclicBarThread(barrier));
                t.start();

            }



        }
    }

And Thread is

        public class CuclicBarThread implements Runnable {

        CyclicBarrier barrier;

        public CuclicBarThread(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                for (int i = 1; i < 5; i++) {
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 1 After Stage 1 Completed");
                barrier.await();

                for (int i = 1; i < 5; i++) {
                    Thread.sleep(1000);
                }
                System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 2 After Stage 2 Completed");
                barrier.await();

                for (int i = 1; i < 5; i++) {
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 3 After Stage 3 Completed");
                barrier.await();
                System.out.println(Thread.currentThread().getName()+" :: $$$$$$$$ Completed $$$$$$$$");
            } catch (Exception ex) {
                ex.printStackTrace();
            }



        }
    }
like image 640
LMK Avatar asked Nov 09 '22 05:11

LMK


1 Answers

Yes it is reusable. That is why it is called "Cyclic". Here is the quote from its JavaDoc:

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

And your usage of the CyclicBarrier seems fine to me.

like image 159
Denis Iskhakov Avatar answered Nov 14 '22 21:11

Denis Iskhakov