Java Concurrency - 浅析 CountDownLatch 的用法
The Java concurrency API provides a class that allows one or more threads to wait until a set of operations are made. It's the CountDownLatch class. This class is initialized with an integer number, which is the number of operations the threads are going to wait for. When a thread wants to wait for the execution of these operations, it uses the await() method. This method puts the thread to sleep until the operations are completed. When one of these operations finishes, it uses the countDown() method to decrement the internal counter of the CountDownLatch class. When the counter arrives to 0, the class wakes up all the threads that were sleeping in the await() method.
Example
In this recipe, you will learn how to use the CountDownLatch class implementing a videoconference system. The video-conference system will wait for the arrival of all the participants before it begins.
Videoconference
/**
* This class implements the controller of the Videoconference
* It uses a CountDownLatch to control the arrival of all the participants in the conference.
*/
public class Videoconference implements Runnable { private final CountDownLatch controller; public Videoconference(int number) {
controller = new CountDownLatch(number);
} /**
* This method is called by every participant when he incorporates to the VideoConference
* @param participant
*/
public void arrive(String name) {
System.out.printf("%s has arrived.\n", name);
// This method uses the countDown method to decrement the internal counter of the CountDownLatch
controller.countDown();
System.out.printf("VideoConference: Waiting for %d participants.\n", controller.getCount());
} /**
* This is the main method of the Controller of the VideoConference.
* It waits for all the participants and then, starts the conference
*/
@Override
public void run() {
System.out.printf("VideoConference: Initialization: %d participants.\n", controller.getCount());
try {
// Wait for all the participants
controller.await();
// Starts the conference
System.out.printf("VideoConference: All the participants have come\n");
System.out.printf("VideoConference: Let's start...\n");
} catch (InterruptedException e) {
e.printStackTrace();
}
} } /**
* This class implements a participant in the VideoConference
*/
public class Participant implements Runnable { /**
* VideoConference in which this participant will take part off
*/
private Videoconference conference; /**
* Name of the participant. For log purposes only
*/
private String name; /**
* Constructor of the class. Initialize its attributes
*/
public Participant(Videoconference conference, String name) {
this.conference = conference;
this.name = name;
} /**
* Core method of the participant. Waits a random time and joins the VideoConference
*/
@Override
public void run() {
Long duration = (long) (Math.random() * 10);
try {
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
conference.arrive(name);
} } /**
* Main class of the example. Create, initialize and execute all the objects necessaries for the example
*/
public class Main {
public static void main(String[] args) {
// Creates a VideoConference with 10 participants.
Videoconference conference = new Videoconference(10);
// Creates a thread to run the VideoConference and start it.
Thread threadConference = new Thread(conference);
threadConference.start(); // Creates 10 participants, a thread for each one and starts them
for (int i = 0; i < 10; i++) {
Participant p = new Participant(conference, "Participant" + i);
Thread t = new Thread(p);
t.start();
} }
}
The CountDownLatch class has three basic elements:
- The initialization value that determines how many events the CountDownLatch class waits for
- The await() method, called by the threads that wait for the finalization of all the events
- The countDown() method, called by the events when they finish their execution
When you create a CountDownLatch object, the object uses the constructor's parameter to initialize an internal counter. Every time a thread calls the countDown() method, the CountDownLatch object decrements the internal counter in one unit. When the internal counter arrives to 0, the CountDownLatch object wakes up all the threads that were waiting in the await() method.
There's no way to re-initialize the internal counter of the CountDownLatch object or to modify its value. Once the counter is initialized, the only method you can use to modify its value is the countDown() method explained earlier. When the counter arrives to 0, all the calls to the await() method return immediately and all subsequent calls to the countDown() method have no effect.
The CountDownLatch class has another version of the await() method, which is given as follows:
await(long time, TimeUnit unit): The thread will be sleeping until it's interrupted; the internal counter of CountDownLatch arrives to 0 or specified time passes. The TimeUnit class is an enumeration with the following constants: DAYS, HOURS, MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS, and SECONDS.
Java Concurrency - 浅析 CountDownLatch 的用法的更多相关文章
- Java Concurrency - 浅析 CyclicBarrier 的用法
The Java concurrency API provides a synchronizing utility that allows the synchronization of two or ...
- Java Concurrency - 浅析 Phaser 的用法
One of the most complex and powerful functionalities offered by the Java concurrency API is the abil ...
- 深入浅出 Java Concurrency (10): 锁机制 part 5 闭锁 (CountDownLatch)
此小节介绍几个与锁有关的有用工具. 闭锁(Latch) 闭锁(Latch):一种同步方法,可以延迟线程的进度直到线程到达某个终点状态.通俗的讲就是,一个闭锁相当于一扇大门,在大门打开之前所有线程都被阻 ...
- 深入浅出 Java Concurrency (10): 锁机制 part 5 闭锁 (CountDownLatch)[转]
此小节介绍几个与锁有关的有用工具. 闭锁(Latch) 闭锁(Latch):一种同步方法,可以延迟线程的进度直到线程到达某个终点状态.通俗的讲就是,一个闭锁相当于一扇大门,在大门打开之前所有线程都被阻 ...
- Java并发编程之CountDownLatch的用法
一.含义 CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能.CountDownLatch是一个同步的辅助类,它可以允许一个或多个线程等待, ...
- JAVA concurrent包下Semaphore、CountDownLatch等用法
CountDownLatch 跟join的区别 CountDownLatch用处跟join很像,但是CountDownLatch更加灵活,如果子线程有多个阶段a.b.c; 那么我们可以实现在a阶段完成 ...
- 《Java Concurrency》读书笔记,使用JDK并发包构建程序
1. java.util.concurrent概述 JDK5.0以后的版本都引入了高级并发特性,大多数的特性在java.util.concurrent包中,是专门用于多线并发编程的,充分利用了现代多处 ...
- Java并发之CountDownLatch、CyclicBarrier和Semaphore
CountDownLatch 是能使一组线程等另一组线程都跑完了再继续跑:CyclicBarrier 能够使一组线程在一个时间点上达到同步,可以是一起开始执行全部任务或者一部分任务. CountDow ...
- java多线程管理 concurrent包用法详解
我们都知道,在JDK1.5之前,Java中要进行业务并发时,通常需要有程序员独立完成代码实现,当然也有一些开源的框架提供了这些功能,但是这些依然没有JDK自带的功能使用起来方便.而当针对高质量 ...
随机推荐
- POJ3630Phone List(字典树)
参考http://s.acmore.net/show_article/show/58 以附上代码 #include<iostream> #include<stdio.h> #i ...
- js中的if判断十分优美的简洁写法
本尊混迹猿人类也有5年有余,从最开始的C#到java再到php到至今的python,不能说精通,也算得上是熟悉,对各个语言的语法也算是了解. 虽然目前在开发web程序,了解一些java知识,但是今天在 ...
- 启用MySQL查询缓存
启用MySQL查询缓存能够极大地减低数据库server的CPU使用率,实际使用情况是:开启前CPU使用率120%左右,开启后降到了10%. 查看查询缓存情况: mysql> show varia ...
- URAL 1784 K - Rounders 找规律
K - RoundersTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vjudge/contest/view. ...
- Android使用百度定位SDK 方法及错误处理
之前我的项目中的位置定位使用的是基站方法,使用的Google提供的API,但是前天中午突然就不返回数据了,到网上搜了一下才知道,Google的接 口不提供服务了,基于时间紧迫用了百度现有的SDK,但是 ...
- MySQL · 引擎特性 · InnoDB COUNT(*) 优化(?)
http://mysql.taobao.org/monthly/2016/06/10/ 在5.7版本中,InnoDB实现了新的handler的records接口函数,当你需要表上的精确记录个数时,会直 ...
- 写了个SharedPreferences的工具类(带加密)
/* * Copyright (C) 2014 Jason Fang ( ijasonfang@gmail.com ) * * Licensed under the Apache License, V ...
- 【天池大数据赛题解析】资金流入流出预测(附Top4答辩ppt)
http://mp.weixin.qq.com/s?__biz=MzA3MDg0MjgxNQ==&mid=208451006&idx=1&sn=532e41cf020a0673 ...
- mysql修改表结构
表 linksus_gov_running_trans 和 linksus_gov_running 的 is_mulsplit_id 字段需要改成 bigint(20)原:`is_mulsplit_i ...
- BootStrap2学习日记6---代码
<:表示“<” >:表示“>” 在BootStrap中标记代码的标签使用<code>,标记代码块使用<pre>(里面的代码特殊标签必须转义) ...