ruijiege

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
package cn.jiedada.controller;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class TestABC {
    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier cyclicBarrier=new CyclicBarrier(3);

        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                // 等待前两个(A/B)线程结束,只有前两个(A/B)线程结束了才能满足3个线程都冲破栅栏,
                try {
                    // 等待栅栏被冲破,冲破栅栏的条件是:A/B/C三个线程都到达await()。
                    // 只有栅栏冲破,才能向下执行,否则先到达的线程等待。
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                    throw new RuntimeException("cylicBarrier.await()拋出異常:",e);
                }
                // 满足了三个线程都冲破栅栏才向下执行
                System.out.println(Thread.currentThread().getName());
            }
        }, "Thread-C");

        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(new java.util.Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());

                // 冲破栅栏代表A线程结束
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                    throw new RuntimeException("cylicBarrier.await()拋出異常:",e);
                }
            }
        }, "Thread-A");

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(new java.util.Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());

                // 冲破栅栏代表B线程结束
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                    throw new RuntimeException("cylicBarrier.await()拋出異常:",e);
                }
            }
        }, "Thread-B");


        threadC.start();
        threadA.start();
        threadB.start();

    }
}

 

posted on 2021-07-14 10:56  哦哟这个怎么搞  阅读(72)  评论(0编辑  收藏  举报