介绍

CountDownLatch是一个同步辅助类,它允许一个或多个线程一直等待直到其他线程执行完毕才开始执行。

用给定的计数初始化CountDownLatch,其含义是要被等待执行完的线程个数。

每次调用CountDown(),计数减1

主程序执行到await()函数会阻塞等待线程的执行,直到计数为0

实现原理

计数器通过使用锁(共享锁、排它锁)实现

实例1

场景:模拟10人赛跑。10人跑完后才喊"Game Over."

package com.jihite;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class CountDownLatchTest {
private static final int RUNNER_COUNT = 10;
public static void main(String[] args) throws InterruptedException {
final CountDownLatch begin = new CountDownLatch(1);
final CountDownLatch end = new CountDownLatch(RUNNER_COUNT);
final ExecutorService exec = Executors.newFixedThreadPool(10); for (int i = 0; i < RUNNER_COUNT; i++) {
final int NO = i + 1;
Runnable run = new Runnable() {
@Override
public void run() {
try {
begin.await();
Thread.sleep((long)(Math.random() * 10000));
System.out.println("No." + NO + " arrived");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
end.countDown();
}
}
};
exec.submit(run);
} System.out.println("Game Start ...");
begin.countDown();
end.await();
// end.await(30, TimeUnit.SECONDS);
System.out.println("Game Over."); exec.shutdown();
}
}

分析:代码中定义了2个计数器,个数分别为1和10。

如果不执行begin.countDown(),进程会一致阻塞在begin.await()

主进程执行到end.awit()阻塞等待end计数器清0,进程中每执行一次CountDown()减1,所有执行完后主进程继续往下执行

输出

Game Start ...
No.6 arrived
No.4 arrived
No.10 arrived
No.3 arrived
No.9 arrived
No.5 arrived
No.8 arrived
No.7 arrived
No.1 arrived
No.2 arrived
Game Over.

注:countDown()一定要执行到(考虑异常及线程与开始计数设置不一致),否则会一直卡在await()(可以设置时间,超过一定时间就不等了)

实例2(和join的相似处)

场景:流水线上有3个worker: worker1、worker2、worker3,只有当worker1和worker2执行完时才可以执行worker3

WorkerCount.java

package com.jihite;

import java.util.concurrent.CountDownLatch;

public class WorkerCount extends Thread {
private String name;
private long time;
private CountDownLatch countDownLatch; public WorkerCount(String name, long time, CountDownLatch countDownLatch) {
this.name = name;
this.time = time;
this.countDownLatch = countDownLatch;
} @Override
public void run() {
try {
System.out.println(name + "开始工作");
Thread.sleep(time);
System.out.println(name + "工作完成, 耗时:"+ time);
countDownLatch.countDown();
System.out.println("countDownLatch.getCount():" + countDownLatch.getCount());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

CountDownLatch实现:

    @Test
public void CountDownLatchTest() throws InterruptedException {
int COUNT = 2;
final CountDownLatch countDownLatch = new CountDownLatch(COUNT);
WorkerCount worker0 = new WorkerCount("lilei-0", (long)(Math.random() * 10000), countDownLatch);
WorkerCount worker1 = new WorkerCount("lilei-1", (long)(Math.random() * 10000), countDownLatch);
worker0.start();
worker1.start();
countDownLatch.await();
System.out.println("准备工作就绪"); WorkerCount worker2 = new WorkerCount("lilei-2", (long)(Math.random() * 10000), countDownLatch);
worker2.start();
Thread.sleep(10000);
}

输出:

lilei-0开始工作
lilei-1开始工作
lilei-1工作完成, 耗时:4039
countDownLatch.getCount():1
lilei-0工作完成, 耗时:9933
countDownLatch.getCount():0
准备工作就绪
lilei-2开始工作
lilei-2工作完成, 耗时:6402
countDownLatch.getCount():0

该场景join也可以完成

Worker.java

package com.jihite;
public class Worker extends Thread{
private String name;
private long time; public Worker(String name, long time) {
this.name = name;
this.time = time;
} @Override
public void run() {
try {
System.out.println(name + "开始工作");
Thread.sleep(time);
System.out.println(name + "工作完成, 耗时:"+ time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

join实现

 @Test
public void JoinTest() throws InterruptedException {
Worker worker0 = new Worker("lilei-0", (long)(Math.random() * 10000));
Worker worker1 = new Worker("lilei-1", (long)(Math.random() * 10000));
Worker worker2 = new Worker("lilei-2", (long)(Math.random() * 10000));
worker0.start();
worker1.start(); worker0.join();
worker1.join();
System.out.println("准备工作就绪"); worker2.start();
Thread.sleep(10000);
}

输出

lilei-0开始工作
lilei-1开始工作
lilei-1工作完成, 耗时:4483
lilei-0工作完成, 耗时:6301
准备工作就绪
lilei-2开始工作
lilei-2工作完成, 耗时:6126

既然这样,那CountDownLatch和join的区别在哪?通过下面的场景三就可以看出

实例3(和join的不同处)

场景:流水线上有3个worker: worker1、worker2、worker3,只有当worker1和worker2两者的阶段一都执行完后才可以执行worker3

WorkerCount2.java

package com.jihite;

import java.util.concurrent.CountDownLatch;

public class WorkerCount2 extends Thread {
private String name;
private long time;
private CountDownLatch countDownLatch; public WorkerCount2(String name, long time, CountDownLatch countDownLatch) {
this.name = name;
this.time = time;
this.countDownLatch = countDownLatch;
} @Override
public void run() {
try {
System.out.println(name + "开始阶段1工作");
Thread.sleep(time);
System.out.println(name + "阶段1完成, 耗时:"+ time);
countDownLatch.countDown(); System.out.println(name + "开始阶段2工作");
Thread.sleep(time);
System.out.println(name + "阶段2完成, 耗时:"+ time); } catch (InterruptedException e) {
e.printStackTrace();
}
}
}

此时用join无法实现,只能用CountDownLatch

 @Test
public void CountDownLatchTest2() throws InterruptedException {
int COUNT = 2;
final CountDownLatch countDownLatch = new CountDownLatch(COUNT);
WorkerCount2 worker0 = new WorkerCount2("lilei-0", (long)(Math.random() * 10000), countDownLatch);
WorkerCount2 worker1 = new WorkerCount2("lilei-1", (long)(Math.random() * 10000), countDownLatch);
worker0.start();
worker1.start();
countDownLatch.await();
System.out.println("准备工作就绪"); WorkerCount2 worker2 = new WorkerCount2("lilei-2", (long)(Math.random() * 10000), countDownLatch);
worker2.start();
Thread.sleep(10000);
}

输出

lilei-0开始阶段1工作
lilei-1开始阶段1工作
lilei-0阶段1完成, 耗时:3938
lilei-0开始阶段2工作
lilei-1阶段1完成, 耗时:6259
lilei-1开始阶段2工作
准备工作就绪
lilei-2开始阶段1工作
lilei-0阶段2完成, 耗时:3938
lilei-1阶段2完成, 耗时:6259
lilei-2阶段1完成, 耗时:7775
lilei-2开始阶段2工作

java多线程对CountDownLatch的使用实例的更多相关文章

  1. Java多线程-----理解CountDownLatch

       CountDownLatch简介  CountDownLatch是在java1.5被引入的,跟它一起被引入的并发工具类还有CyclicBarrier.Semaphore.ConcurrentHa ...

  2. java 多线程 day16 CountDownLatch 倒计时计数器

    import java.util.concurrent.CountDownLatch;import java.util.concurrent.CyclicBarrier;import java.uti ...

  3. Java多线程:CountDownLatch、CyclicBarrier 和 Semaphore

    场景描述: 多线程设计过程中,经常会遇到需要等待其它线程结束以后再做其他事情的情况. 有几种方案:   1.在主线程中设置一自定义全局计数标志,在工作线程完成时,计数减1.主线程侦测该标志是否为0,一 ...

  4. java多线程并发控制countDownLatch和cyclicBarrier的使用

    java主线程等待所有子线程执行完毕在执行,这个需求其实我们在工作中经常会用到,比如用户下单一个产品,后台会做一系列的处理,为了提高效率,每个处理都可以用一个线程来执行,所有处理完成了之后才会返回给用 ...

  5. java 多线程通知 CountDownLatch 倒数计数器的使用

    package com.hra.riskprice; import com.hra.riskprice.SysEnum.Factor_Type; import org.springframework. ...

  6. Java 多线程系列 CountDownLatch

    CountDownLatch 一个或多个线程等待其他线程完成操作后在在执行 CountDownLatch通过一个计数器来实现,await方法阻塞直到 countDown() 调用计数器归零之后释放所有 ...

  7. Java多线程(3):wait()/notify()实例

    下面是代码实例 public class WaitDemo implements Runnable { private Object lock; public WaitDemo(Object lock ...

  8. 图解java多线程设计模式之一一synchronized实例方法体

    synchronized实例方法体和synchronized代码块 synchronied void method(){ ....... } 这个等同于下面将方法体用synchronized(this ...

  9. 《Java多线程编程核心技术》推荐

    写这篇博客主要是给猿友们推荐一本书<Java多线程编程核心技术>. 之所以要推荐它,主要因为这本书写得十分通俗易懂,以实例贯穿整本书,使得原本抽象的概念,理解起来不再抽象. 只要你有一点点 ...

随机推荐

  1. 【一天一道LeetCode】#45. Jump Game II

    一天一道LeetCode系列 (一)题目 Given an array of non-negative integers, you are initially positioned at the fi ...

  2. Android View底层到底是怎么绘制的

    Android绘制链图: 网上很多讲Android  view的绘制流程往往只讲到了Measure - Layout - Draw. 但是,这只是一个大体的流程,而我们需要探讨的是Android在我们 ...

  3. 【UML 建模】UML入门 之 交互图 -- 时序图 协作图详解

    . 作者 : 万境绝尘 转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/17927131 . 动态图概念 : 从静态图中抽取瞬间值 ...

  4. 关于使用Xcode自带的单元测试UnitTest的介绍

    什么是单元测试? 单元测试就是为你的方法专门多写一个测试函数.以保证你的方法在不停的修改开发中.保持正确.如果出错,第一时间让你知道,这样从最小单位开始监控来保证软件的质量. 什么时候用到单元测试: ...

  5. 使用Multiplayer Networking做一个简单的多人游戏例子-1/3(Unity3D开发之二十五)

    猴子原创,欢迎转载.转载请注明: 转载自Cocos2Der-CSDN,谢谢! 原文地址: http://blog.csdn.net/cocos2der/article/details/51006463 ...

  6. 虚拟机安装Ubuntu14.04打开FireFox提示Server not found

    虚拟机安装Ubuntu14.04打开FireFox提示Server not found 我采用VMware安装ubuntu14.04的,VMware的网络是配置采用NAT模式(用于共享主机的IP地址) ...

  7. linux内核 container_ofC语言之应用

    之前在剖析内核链表的文章中就有说到这个 container_of宏展开后的应用技巧. //offset(struct list , list);----->展开后((size_t) & ...

  8. 在SD/MMC卡上实现hive (Implement WinCE HIVE&ROM system on NAND or SD system )

    本是个很简单的topic,但无奈的是很多客户都没有实现.所以只能写一个guide给客户,让他们依葫芦画瓢. 在SD卡上实现hive以及实现binfs最精髓的思想是,在boot stage 1依次加载s ...

  9. PS 滤镜——平面坐标变换到极坐标

    %%% orthogonal coordinate to polar coordinate %%% 平面坐标转极坐标 clc; clear all; close all; addpath('E:\Ph ...

  10. win7待机时间设置,睡眠时间设置

    首先,单击"开始"找到"控制面板" 步骤阅读 2 打开"控制面板"以后,单击右侧的"硬件和声音" 步骤阅读 3 找到&q ...