首页 > 技术文章 > Java系列文章 >

线程并发控制:CountDownLatch闭锁

更新时间:2018-10-08 | 阅读量(865)

## **1.闭锁作用** Latch中文含义有门闩之意,闭锁的作用相当于一扇门:CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成了任务,然后在CountDownLatch上等待的线程就可以恢复执行任务。 ## **2.闭锁的使用场景** 确保某个计算在其需要的所有资源都被初始化之后才继续执行。 确保某个服务在其依赖的所有其他服务都已经启动之后才启动。 等待直到某个操作的所有参与者都就绪再继续执行。 **需求1:计算10个学生抢苹果的总时间。** 问题代码: ``` public class NoCountDownLatchDemo { public static void main(String[] args) throws InterruptedException { long begin = System.currentTimeMillis(); Apple apple = new Apple(); for (int i = 0; i < 10; i++) { new Thread(apple).start(); } long end = System.currentTimeMillis(); System.out.println("共耗费" + (end - begin) + "ms时间"); } } class Apple implements Runnable { private int appleNum = 100; @Override public void run() { for (int i = 0; i < 1000; i++) { synchronized (this) { if (appleNum > 0) { System.out.println(Thread.currentThread().getName() + "抢到第" + appleNum-- + "个苹果"); } } } } } ``` 测试结果: ![image.png](https://upload-images.jianshu.io/upload_images/11046805-dd548e90f8ff431f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 问题分析: 耗费总时间应该是苹果抢完之后才计算出来的,现在还在抢的过程中就计算出来了,所以我们需要在计算消耗时间之前设置一个关卡,判断抢苹果线程是否都结束,如果都结束了就执行时间的计算。 分析如图所示: ![image.png](https://upload-images.jianshu.io/upload_images/11046805-b0ccd3983c95880b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 正确代码: ``` public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(10); long begin = System.currentTimeMillis(); Apple1 apple = new Apple1(latch); for (int i = 0; i < 10; i++) { new Thread(apple).start(); } latch.await();//不让main线程往下运行,直到吃苹果线程都运行完毕,才放行 long end = System.currentTimeMillis(); System.out.println("共耗费"+(end-begin)+"ms时间"); } } class Apple1 implements Runnable{ private int appleNum = 100; private CountDownLatch latch; public Apple1(CountDownLatch latch) { this.latch = latch; } @Override public void run() { try { for (int i = 0; i < 1000; i++) { synchronized (this) { if (appleNum>0) { System.out.println(Thread.currentThread().getName()+"抢到第"+appleNum--+"个苹果"); } } } } finally {//必须要执行 latch.countDown(); } } } ``` **需求2:10个运动员准备赛跑,他们等待裁判一声令下就开始同时跑,当最后一个人通过终点的时候,比赛结束。** ``` public class CountDownLatchDemo2 { public static void main(String[] args) throws InterruptedException { CountDownLatch begin = new CountDownLatch(1); CountDownLatch end = new CountDownLatch(10); long beginTime = System.currentTimeMillis(); Sportsman sportsman = new Sportsman(begin, end); for (int i = 0; i < 10; i++) { new Thread(sportsman).start(); } Thread.sleep(3000);//起跑线上等待3秒,3,2,1 begin.countDown(); // 裁判一声令下开始跑 end.await();// 所有选手到达终点 long endTime = System.currentTimeMillis(); System.out.println("共耗费" + (endTime - beginTime) + "ms时间"); } } class Sportsman implements Runnable { private CountDownLatch begin; private CountDownLatch end; public Sportsman(final CountDownLatch begin, final CountDownLatch end) { this.begin = begin; this.end = end; } @Override public void run() { try { System.out.println(Thread.currentThread().getName() + "预备起跑"); begin.await();// 等待所有线程准备完毕 System.out.println(Thread.currentThread().getName() + "跑步中"); } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.println(Thread.currentThread().getName() + "到达终点"); end.countDown();// 终点计数器,减一 } } } ```
叩丁狼学员采访 叩丁狼学员采访
叩丁狼头条 叩丁狼头条
叩丁狼在线课程 叩丁狼在线课程