CountDownLatch

CountDownLatch

public class Test {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for (int i = 1; i <= 5 ; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"离开教室");
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
        /**
         * 执行到main线程中的await方法时,如果count不为零,则该线程应当阻塞,只有等到coun减为0(即五位学生全部离开教室),由于count不为零而阻塞的线程被唤醒继续执行(锁门操作)
         */

        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"最后离开教室,锁门");
    }
}

输出结果

1离开教室
2离开教室
3离开教室
4离开教室
5离开教室
main最后离开教室,锁门
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值