Semaphore和CountDownLatch

1、 Semaphore信号量共享锁,创建锁时传入的参数代表一次放行几个线程。下边的例子模拟了排队进厕所的场景,保安一次放行2个人进去蹲坑

private void semDemo() {
        Semaphore semaphore = new Semaphore(2);
        for (int i = 0; i < 8; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "开始蹲坑");
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, "编号" + i).start();
        }
    }

2、 CountDownLatch,另外一种共享锁,下边的例子模拟了上船的场景,一条船只能坐五个人,当人数够了五个之后就开船

private void CountDownDemo() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executorService.execute(() -> {
                try {
                    Random random = new Random();
                    int a = random.nextInt(10000);
                    Thread.sleep(a);
                    if(countDownLatch.getCount() <= 0){
                        System.out.println("乘客" + finalI + "未上船,因为船已经满员开走");
                    } else {
                        System.out.println("乘客" + finalI + "已上船,耗时" + a + "毫秒");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        System.out.println("船已经满员,开船");
        executorService.shutdown();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值