简体   繁体   English

CyclicBarrier重复使用示例

[英]CyclicBarrier re-use Example

Does CyclicBarrier best suitable, in this case. 在这种情况下,CyclicBarrier最适合吗? I want to run n threads parallel in Stages (wait at Stages until all threads completes that Stage). 我想在Stages中并行运行n个线程(等待Stages直到所有线程完成该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();
            }



        }
    }

Yes it is reusable. 是的,它是可重复使用的。 That is why it is called "Cyclic". 这就是它被称为“循环”的原因。 Here is the quote from its JavaDoc : 以下是其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. CyclicBarriers在涉及固定大小的线程方的程序中很有用,这些线程必须偶尔等待彼此。 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. 你对CyclicBarrier的使用对我来说似乎很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM