多线程 13 java5的CyclicBarrier同步工具

循环的路障,可以进行反复的使用。

public class CyclicBarrierTest {

    public static void main(String[] args) {

        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        final CyclicBarrier barrier = new CyclicBarrier(3);

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

            Runnable runnable = new Runnable() {

                @Override

                public void run() {

                    try {

                        System.out.println("线程:" + Thread.currentThread().getName() + "即将--到达集合点A");

                        Thread.sleep((long) (Math.random() * 10000));

                        System.out.println("线程:" + Thread.currentThread().getName() + "已经--到达集合点A");

                        barrier.await();

                        System.out.println("线程:" + Thread.currentThread().getName() + "即将--到达集合点B");

                        Thread.sleep((long) (Math.random() * 10000));

                        System.out.println("线程:" + Thread.currentThread().getName() + "已经--到达集合点B");

                        barrier.await();

                        System.out.println("线程:" + Thread.currentThread().getName() + "即将--到达集合点C");

                        Thread.sleep((long) (Math.random() * 10000));

                        System.out.println("线程:" + Thread.currentThread().getName() + "已经--到达集合点C");

                        barrier.await();

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    } catch (BrokenBarrierException e) {

                        e.printStackTrace();

                    }

 

                }

            };

            cachedThreadPool.execute(runnable);

        }

    }

}

如有疑问,请发邮件:[email protected]


github:??https://github.com/wangrui0/

猜你喜欢

转载自blog.csdn.net/qq_35524586/article/details/84983112