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 的用法的更多相关文章

  1. Java Concurrency - 浅析 CyclicBarrier 的用法

    The Java concurrency API provides a synchronizing utility that allows the synchronization of two or ...

  2. Java Concurrency - 浅析 Phaser 的用法

    One of the most complex and powerful functionalities offered by the Java concurrency API is the abil ...

  3. 深入浅出 Java Concurrency (10): 锁机制 part 5 闭锁 (CountDownLatch)

    此小节介绍几个与锁有关的有用工具. 闭锁(Latch) 闭锁(Latch):一种同步方法,可以延迟线程的进度直到线程到达某个终点状态.通俗的讲就是,一个闭锁相当于一扇大门,在大门打开之前所有线程都被阻 ...

  4. 深入浅出 Java Concurrency (10): 锁机制 part 5 闭锁 (CountDownLatch)[转]

    此小节介绍几个与锁有关的有用工具. 闭锁(Latch) 闭锁(Latch):一种同步方法,可以延迟线程的进度直到线程到达某个终点状态.通俗的讲就是,一个闭锁相当于一扇大门,在大门打开之前所有线程都被阻 ...

  5. Java并发编程之CountDownLatch的用法

    一.含义 CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能.CountDownLatch是一个同步的辅助类,它可以允许一个或多个线程等待, ...

  6. JAVA concurrent包下Semaphore、CountDownLatch等用法

    CountDownLatch 跟join的区别 CountDownLatch用处跟join很像,但是CountDownLatch更加灵活,如果子线程有多个阶段a.b.c; 那么我们可以实现在a阶段完成 ...

  7. 《Java Concurrency》读书笔记,使用JDK并发包构建程序

    1. java.util.concurrent概述 JDK5.0以后的版本都引入了高级并发特性,大多数的特性在java.util.concurrent包中,是专门用于多线并发编程的,充分利用了现代多处 ...

  8. Java并发之CountDownLatch、CyclicBarrier和Semaphore

    CountDownLatch 是能使一组线程等另一组线程都跑完了再继续跑:CyclicBarrier 能够使一组线程在一个时间点上达到同步,可以是一起开始执行全部任务或者一部分任务. CountDow ...

  9. java多线程管理 concurrent包用法详解

        我们都知道,在JDK1.5之前,Java中要进行业务并发时,通常需要有程序员独立完成代码实现,当然也有一些开源的框架提供了这些功能,但是这些依然没有JDK自带的功能使用起来方便.而当针对高质量 ...

随机推荐

  1. JQuery中的AJAX参数详细介绍

    Jquery中AJAX参数详细介绍 参数名 类型 描述 url String    (默认: 当前页地址) 发送请求的地址. type String (默认: "GET") 请求方 ...

  2. Codeforces Round #353 (Div. 2) D. Tree Construction (二分,stl_set)

    题目链接:http://codeforces.com/problemset/problem/675/D 给你一个如题的二叉树,让你求出每个节点的父节点是多少. 用set来存储每个数,遍历到a[i]的时 ...

  3. Python 3.2: 使用pymysql连接Mysql

    在python 3.2 中连接MYSQL的方式有很多种,例如使用mysqldb,pymysql.本文主要介绍使用Pymysql连接MYSQL的步骤 1        安装pymysql ·       ...

  4. VS2012与NUnit

    微软提供的NUnit插件是针对vs2010的,而vs2012会自动识别,测试环境为64位win7,具体操作步骤如下 1.下载安装NUnit(NUnit-2.6.3.msi) 2.新建测试项目UnitT ...

  5. Linux学习笔记--(1)

    今天用Linux 的 test 命令,发现了一个有趣的现象: 打入 " test "abc"="abc" ;echo $? " 后,结果应该 ...

  6. Squid 日志详解

    原文地址: http://www.php-oa.com/2008/01/17/squid-log-access-store.html access.log 日志 在squid中access访问日志最为 ...

  7. C语言signal处理的小例子

    [pgsql@localhost tst]$ cat sig01.c #include <stdio.h> #include <signal.h> static void tr ...

  8. Struts2内建校验器(基于校验框架的文件校验)

    位于xwork-2.0.4.jar压缩包中( com.opensymphony.xwork2.validator.validators)有个文件default.xml ,该文件中定义了Struts2框 ...

  9. Codeforces Round #330 (Div. 2) A. Vitaly and Night 暴力

    A. Vitaly and Night Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/595/p ...

  10. [Mapreduce]eclipse下写wordcount

    上传两个文件到hdfs上的input目录下 代码例如以下: import java.io.IOException; import java.util.StringTokenizer; import o ...