JUC-CyclicBarrier

2022-3-13 diaba 多线程

package com.jiucaiyuan.net.juc.lock;

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

/**
 * 循环栅栏
 * 集齐7龙珠召唤神龙
 *
 * @Author jiucaiyuan  2022/3/13 22:48
 * @mail services@jiucaiyuan.net
 */

public class CyclicBarrierDemo {
    public static final Integer NUMBER = 7;

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER, () -> {
            System.out.println("集齐7颗龙珠可以召唤神龙");
        });

        for (int i = 1; i <= NUMBER; i++) {
             new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"星龙珠收集到");
                 try {
                     cyclicBarrier.await();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 } catch (BrokenBarrierException e) {
                     e.printStackTrace();
                 }
             },String.valueOf(i)).start();

        }
    }
}

发表评论:

Powered by emlog 京ICP备15045175号-1 Copyright © 2022