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自带的功能使用起来方便.而当针对高质量 ...
随机推荐
- HDU 4489 The King’s Ups and Downs (DP+数学计数)
题意:给你n个身高高低不同的士兵.问你把他们按照波浪状排列(高低高或低高低)有多少方法数. 析:这是一个DP题是很明显的,因为你暴力的话,一定会超时,应该在第15个时,就过不去了,所以这是一个DP计数 ...
- CSS实现子级窗口高度随低级窗口高度变化
纯粹使用使用height:100%;或者height:auto;来定义内部容器自适应高度,都无法实现让内部容器高度随着外部父容器高度变化而变化,所以我们必需要使用position绝对定位属性来配合协助 ...
- 再次理解JavaScript原型链和匿名函数
<!--------------------------------------------- 1.演示匿名加载 2.js单进程执行流 3.原型链理解 a.__proto__:属性每个对象都有 ...
- Squid代理服务器&&搭建透明代理网关服务器
案例需求 ——公司选用RHEL5服务器作为网关,为了有效节省网络带宽.提高局域网访问Internet的速度,需要在网关服务器上搭建代理服务,并结合防火墙策略实现透明代理,以减少客户端的重复设置工作 需 ...
- JSON API in Javascript
1. Serialize JavaScript object to JSON var messageObject = { title: 'Hello World!', body: 'It\'s gr ...
- JQuery UI Widget Factory官方Demo
<!doctype html> <html lang="en"> <head> <meta charset="utf-8&quo ...
- Codeforces Gym 100523E E - Gophers SET
E - GophersTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vjudge/contest/view.a ...
- 【ZZ】一张图清晰追溯数据库的发展历程(1962-2016年)
http://www.cbdio.com/BigData/2016-02/24/content_4651751.htm 历史发展概述
- C#综合揭秘——Entity Framework 并发处理详解
引言 在软件开发过程中,并发控制是确保及时纠正由并发操作导致的错误的一种机制.从 ADO.NET 到 LINQ to SQL 再到如今的 ADO.NET Entity Framework,.NET 都 ...
- 判断脚本,图片,CSS,iframe等是否加载完成
1.图片 <img id="MyImg" src="src"/>jquery实现:$("#MyImg").load(functi ...