JUC(四)---JUC下常用的辅助类(CountDownLatch.CyclicBarrier,Semaphore)

一.CountDownLatch—计数器

在这里插入图片描述
代码测试:

public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        // 总数是6,必须要等执行完6个线程后才能执行await下面的代码
        //例如:有6个学生,一定要等6个学生走完后才能关门
       CountDownLatch countDownLatch = new CountDownLatch(6);
       for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "Go Out");
                countDownLatch.countDown();// 数量-1
            }, String.valueOf(i)).start();
        }

       countDownLatch.await(); // 等待计数器归零,然后再向下执行
       System.out.println("关门");
    }
}

在这里插入图片描述
原理:
countDownLatch.countDown(); // 数量-1
countDownLatch.await(); // 等待计数器归零,然后再向下执行
每次有线程调用 countDown() 数量-1,假设计数器变为0,countDownLatch.await() 就会被唤醒,继续执行!

二.CyclicBarrier—加法计数器

在这里插入图片描述

public class CyclicBarrierTest {
    public static void main(String[] args) {
        /**
         * 集齐7颗龙珠召唤神龙
         */
        //召唤神龙的过程
        CyclicBarrier cyclicBarrier=new CyclicBarrier(7,()-> System.out.println("集齐7颗龙珠,召唤神龙"));

        for (int i = 1; i <=7; i++) {
            final int temp=i;
            new Thread(()-> {
                try {
                    System.out.println(Thread.currentThread().getName()+"收集"+temp+"个龙珠");

                    cyclicBarrier.await();//等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

在这里插入图片描述

三.Semaphore----信号量

在这里插入图片描述
例如:抢车位问题:6车----3个停车位

public class SemaphoreTest {
    public static void main(String[] args) {
        //线程数量:停车位,可以用于限流
        Semaphore semaphore=new Semaphore(3);

        for (int i = 1; i <=6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();//得到
                    System.out.println(Thread.currentThread().getName()+"拿到车位");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName()+"离开车位");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();// release() 释放
                }
            }).start();
        }
    }
}

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值