Java 多线程高并发 3.6 — CountDownLatch 简单使用

  1. 按照名字理解是 计数锁
  2. 用于多线程并行的同步,起栅栏作用
  3. 做法是利用计数器计算还未完成的任务数,直到计数为 0 的时候,才会往下执行
  4. 有点类似于线程对象的 join() 方法,都是等待子线程执行完毕再往下走
  5. 如果线程数大于计数器的数量,则同样计数为 0 的时候立刻往下执行
  6. 貌似挺简单的,需要根据业务场景灵活运用
  7. 下面看原理图
    CountDownLatch
    放码过来
public class TestCountDownLatch {
	
	private static CountDownLatch cdl = new CountDownLatch(5);
	
	static class TestThread implements Runnable {
		@Override
		public void run() {
			try {
				Thread.sleep(new Random().nextInt(10) * 1000);
				System.out.println(System.currentTimeMillis() + " :" + Thread.currentThread().getName() + " 进来了,"
						+ " 当前 countDown:" + cdl.getCount());
				cdl.countDown();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		System.out.println("======= 开始测试 CountDownLatch =======");
		Thread[] threads = new Thread[10];
		TestThread read = new TestThread();
		for (int i = 0; i < threads.length; i++) threads[i] = new Thread(read, "线程 " + i);
		for (int i = 0; i < threads.length; i++) threads[i].start();
		cdl.await();
		System.out.println("======= 全部线程检查完毕,程序退出 =======");
	}
}

======= 开始测试 CountDownLatch =======
1537881097774 :线程 8 进来了, 当前 countDown:5
1537881097774 :线程 2 进来了, 当前 countDown:5
1537881097774 :线程 6 进来了, 当前 countDown:5
1537881098775 :线程 0 进来了, 当前 countDown:2
1537881100775 :线程 1 进来了, 当前 countDown:1
1537881100775 :线程 4 进来了, 当前 countDown:1


======= 全部线程检查完毕,程序退出 =======
1537881101775 :线程 5 进来了, 当前 countDown:0
1537881104775 :线程 3 进来了, 当前 countDown:0
1537881105775 :线程 9 进来了, 当前 countDown:0
1537881106775 :线程 7 进来了, 当前 countDown:0

这里要提一下的是:

  • CountDownLatch 不能重复使用,countDown 完了只能重新实例化一个出来
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值