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自带的功能使用起来方便.而当针对高质量 ...
随机推荐
- MongoDB的update有关问题(JAVA)——如何一次更新所有的相同记录
MongoDB的update问题(JAVA)——怎么一次更新所有的相同记录用如下这个函数:public WriteResult update(DBObject q, DBObject o, boo ...
- 剑指OFFER之变态跳台阶(九度OJ1389)
题目描述: 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级.求该青蛙跳上一个n级的台阶总共有多少种跳法. 输入: 输入可能包含多个测试样例,对于每个测试案例, 输入包括一个整数n(1 ...
- mac ide
常用IDE xcode sublime text eclipse xampp + phpstorm sql客户端:sequel pro 虚拟机:parallels desktop sftp客户端:Cy ...
- Cocos2d-x——支持多触点
1:在AppController的didFinishLaunchingWithOptions中,加入 [__glView setMultipleTouchEnabled:YES]; 2:在CCLaye ...
- ListView为什么用setOnItemClick这个方法和onTouch这个方法有冲突
因为如果onTouch方法中返回true的话,这次事件就被ListView中的item控件消费了,所以不会执行ListVIew的setOnItemClick这个方法了,如果onTouch方法返回fal ...
- PostgreSQL的 initdb 源代码分析之十六
继续分析 setup_description(); 展开后: 就是要把 share/postgres.description 文件的内容读入到 pg_description 和 pg_shdescri ...
- 【M20】协助完成“返回值优化(RVO)”
1.方法返回对象,会导致临时对象的产生,这降低了效率,const Rational operator* (const Rational& lhs,Rational& rhs).有没有什 ...
- Codeforces Round #327 (Div. 2) C. Median Smoothing 找规律
C. Median Smoothing Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/591/p ...
- 通过程序 VB.Net 或 C# 读取文本文件行数
1, VB.NET 读取 (通过streamReader) ' tmpCount = 0 'Dim tmpSR As New StreamReader(fileFullName, System.Tex ...
- Hibernate征途(七)之复合主键映射和集合映射
把这两种映射放到一起说,是因为这两种映射不像前面的复用型映射.数量和方向型映射那么分类鲜明,所以放到了这个“其他”里面. 复合主键映射 在关系模型中,复合主键和其他的主键方式没有很大区别,但是反映到对 ...