同步器-倒计时门闩

Java中虽然提供了synchronized关键字对临界区进行线程同步访问,但是基于synchronized很难正确地编写同步代码,而倒计时门闩可以让一条或多条线程在“门口”一直等待,直到门闩的计数变量为0,线程才可以继续执行。

组成

类java.util.concurrent.CountDownLatch实现了倒计时门闩同步器,它是由一个计数变量和两个操作数组成的,这两个操作分别是“导致一条线程等待直到计数变为0”以及“递减计数变量”

主要方法
  • CountDownLatch(int count):count是计数个数,当count的值是负数时,会抛出Exception

  • void await():除非线程被中断,否则强制调用线程一直等到计数倒数到0.中断时会抛出Exception

  • void countDown():递减计数,当计数降至0时,释放所有等待线程。当该方法被调用时count已经为0,那么 什么也不会发生

  • long getCount():返回当前的计数

示例程序
public class CountDownLatchDemo {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.print(Thread.currentThread() + ": in this thread latch count is " + countDownLatch.getCount() + "\n");
                countDownLatch.countDown();
                System.out.print(Thread.currentThread() +": after count down, latch count is " + countDownLatch.getCount() + "\n");
            }
        };
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        System.out.print("before latch await\n");
        for (int i = 0; i < 3; i ++) {
            executorService.execute(runnable);
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.print("main thread work again\n");
    }
}

在这个示例中,有三个子线程和一个主线程,主线程调用await方法之后一直等待,直到倒计时门闩中的计数变量变为0才继续执行,结果如下:

before latch await
Thread[pool-1-thread-2,5,main]: in this thread latch count is 3
Thread[pool-1-thread-1,5,main]: in this thread latch count is 3
Thread[pool-1-thread-2,5,main]: after count down, latch count is 2
Thread[pool-1-thread-3,5,main]: in this thread latch count is 3
Thread[pool-1-thread-1,5,main]: after count down, latch count is 1
Thread[pool-1-thread-3,5,main]: after count down, latch count is 0
main thread work again

这里需要注意的是,并不是每次都会先打印子线程中的信息,可能会出现在子线程执行完countDown()方法之后,countLatchDown中的计数变量已经为0,主线程已经可以执行,这时cpu先执行了主线程中的print语句,之后再去执行子线程中的print语句。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值