一个例子让你了解多线程闭锁

闭锁:确保多个线程在完成各自事务后,才会打开继续执行后面的内容,否则一直等待。

  • 例子1:执行线程打印一下执行的时间
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <= 10; i++) {
                    System.out.println(i);
                }
            }
        }).start();
        long end = System.currentTimeMillis();
        System.out.println("===>"+ (end-start));
    }
}

结果:执行时间在前面就打印了

===>4
0
1
2
3
4
5
6
7
8
9
10

怎么让打印执行时间在后面才执行呢,那就要到闭锁了(CountDownLatch),优化一下

public class ThreadDemo2 implements Runnable {

    private final CountDownLatch latch;

    public ThreadDemo2(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5000; i++) {
            System.out.println(i);
        }
        latch.countDown();//当前事件执行完毕,计数 -1
    }

    public static void main(String[] args) {
        // 申明,等待事件数量 5次
        CountDownLatch latch = new CountDownLatch(5);

        // 依次创建并启动处于等待状态的5个线程
        ThreadDemo2 threadDemo2 = new ThreadDemo2(latch);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5; i++) {
            new Thread(threadDemo2).start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("===>"+ (end-start));
    }
}

 结果:CountDownLatch 内部维护一个计数器(new CountDownLatch(5)),当 latch.countDown() 的时候计数会减1,latch.await() 的时候等待计数器 = 0,所有await的线程都会阻塞,直到计数器为0或者等待线程中断或者超时。

...
6
7
8
9
10
===>4

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值