CountDownLatch是一个同步辅助类,犹如倒计时计数器,创建对象时通过构造方法设置初始值,调用CountDownLatch对象的await()方法则使当前线程处于等待状态,调用countDown()方法就将计数器减1,当计数到达0时,则所有等待线程全部开始执行。它提供的常用方法:

 public CountDownLatch(int count);   //构造方法参数指定了计数的次数

 public void countDown();           //当前线程调用此方法,则计数减一

 public void await() throws InterruptedException;   //调用此方法会一直阻塞当前线程,直到计时器的值为0

使用方式如下:

package basic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class TestCountDown { private static final int PLAYER_AMOUNT = 5; public static void main(String[] args) {
/* 对于每位运动员,CountDownLatch减1后即开始比赛 */
CountDownLatch begin = new CountDownLatch(1);
/* 对于整个比赛,所有运动员结束后才算结束 */
CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT);
Player[] players = new Player[PLAYER_AMOUNT];
for (int i = 0; i < PLAYER_AMOUNT; i++) {
players[i] = new Player(i + 1, begin, end);
}
/* 设置特定的线程池,大小为5 */
ExecutorService executorService = Executors.newFixedThreadPool(PLAYER_AMOUNT);
for (Player player : players) {
/* 分配线程 */
executorService.execute(player);
}
System.out.println("Race begins!");
/* 所有Player等待 比赛信号的开始 */
begin.countDown();
try {
/* 等待end状态变为0,即为比赛结束 */
end.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Race ends!");
}
executorService.shutdown();
}
} class Player implements Runnable { private final int id;
private final CountDownLatch begin;
private final CountDownLatch end; public Player(int id, CountDownLatch begin, CountDownLatch end){
super();
this.id = id;
this.begin = begin;
this.end = end;
} @Override
public void run() {
try {
/* 等待begin的状态为0 */
begin.await();
/* 随机分配时间,即运动员完成时间 */
Thread.sleep((long) (Math.random() * 100));
System.out.println("Play" + id + "arrived.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
/* 使end状态减1,当前线程的运动员完成比赛 */
end.countDown();
}
} }

代码中begin.countDown()是比赛信号开始,五个begin.await()的线程开始执行,执行完之后在finally块中执行end.countDown(),当计数器减为0的时候,唤醒main方法中的end.await(),程序接着往下执行,打印比赛结束。

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted. If the current count is zero then this method returns immediately. If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happen:   1.The count reaches zero due to invocations of the countDown() method; or   2.Some other thread interrupts the current thread.

If the current thread: has its interrupted status set on entry to this method; or is interrupted while waiting, then java.lang.InterruptedException is thrown and the current thread's interrupted status is cleared. Throws: java.lang.InterruptedException if the current thread is interrupted while waiting public void await() throws InterruptedException {   sync.acquireSharedInterruptibly(1); }

上面是核心方法await()的JDK源码!

同步辅助类CountDownLatch用法的更多相关文章

  1. JAVA线程同步辅助类CountDownLatch

    一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待. 用给定的计数 初始化 CountDownLatch.由于调用了 countDown() 方法,所以在当前计数到达 ...

  2. 线程中的同步辅助类CountDownLatch

    四个类可协助实现常见的专用同步语句.Semaphore 是一个经典的并发工具.CountDownLatch 是一个极其简单但又极其常用的实用工具,用于在保持给定数目的信号.事件或条件前阻塞执行.Cyc ...

  3. 利用同步辅助类CountDownLatch计算多线程的运行时间

    一.CountDownLatch jdk提供的一个同步辅助类,在完成一组在在其他线程中执行的操作前,允许一个或者多个其他的线程等待,通过调用 await() 方法阻塞,直到由于 countDown() ...

  4. java并发之同步辅助类CountDownLatch

    CountDownLatch 含义: CountDownLatch可以理解为一个计数器在初始化时设置初始值,当一个线程需要等待某些操作先完成时,需要调用await()方法.这个方法让线程进入休眠状态直 ...

  5. CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

    CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待. 主要方法 public CountDownLatch(int count); pu ...

  6. java并发之同步辅助类(Semphore、CountDownLatch、CyclicBarrier、Phaser)

    线程同步辅助类,主要学习两点: 1.上述几种同步辅助类的作用以及常用的方法 2.适用场景,如果有适当的场景可以用到,那无疑是最好的 semaphore(seməˌfôr) 含义 信号量就是可以声明多把 ...

  7. Java并发编程的4个同步辅助类(CountDownLatch、CyclicBarrier、Semaphore、Phaser)

    我在<JDK1.5引入的concurrent包>中,曾经介绍过CountDownLatch.CyclicBarrier两个类,还给出了CountDownLatch的演示案例.这里再系统总结 ...

  8. Java并发编程的4个同步辅助类(CountDownLatch、CyclicBarrier、Semphore、Phaser)

    我在<jdk1.5引入的concurrent包>中,曾经介绍过CountDownLatch.CyclicBarrier两个类,还给出了CountDownLatch的演示案例.这里再系统总结 ...

  9. CountDownLatch同步辅助类

    CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待. 主要方法 public CountDownLatch(int count); pu ...

随机推荐

  1. ASP.NET MVC5----常见的数据注解和验证

    只要一直走,慢点又何妨. 在使用MVC模式进行开发时,数据注解是经常使用的(模型之上操作),下面是我看书整理的一些常见的用法. 什么是验证,数据注解 验证 从全局来看,发现逻辑仅是整个验证的很小的一部 ...

  2. FreeMarker:怎么使用

    第一个FreeMarker程序 1. 建立一个普通的java项目:testFreeMarker 2. 引入freemarker.jar包 3. 在项目目录下建立模板目录:templates 4. 在t ...

  3. JavaScript将字符串中的每一个单词的第一个字母变为大写其余均为小写

    要求: 确保字符串的每个单词首字母都大写,其余部分小写. 这里我自己写了两种方法,或者说是一种方法,另一个是该方法的变种. 第一种: function titleCase(str) { var new ...

  4. 深入理解DOM节点操作

    × 目录 [1]创建节点 [2]插入节点 [3]移除节点[4]替换节点[5]复制节点 前面的话 一般地,提起操作会想到“增删改查”这四个字,而DOM节点操作也类似地对应于此,接下来将详细介绍DOM的节 ...

  5. 让你从零开始学会写爬虫的5个教程(Python)

    写爬虫总是非常吸引IT学习者,毕竟光听起来就很酷炫极客,我也知道很多人学完基础知识之后,第一个项目开发就是自己写一个爬虫玩玩. 其实懂了之后,写个爬虫脚本是很简单的,但是对于新手来说却并不是那么容易. ...

  6. 烂泥:jira7.2安装、中文及破解

    . jira的主要配置文件,存放在/opt/atlassian/jira/conf/server.xml文件中,如下: vim /opt/atlassian/jira/conf/server.xml ...

  7. 搭建个人wordpress博客(小白教程)

    新浪sae平台现在是有个免费个人空间使用,现在,教您如何使用该平台搭建属于自己的个人网站,本教程以wordpress程序安装包搭建个人网站. 申请新浪云账号 如果我们使用SAE新浪云计算平台作为服务器 ...

  8. 论C#之多继承

    C#多继承的讨论似乎是个古老的问题了,但今天本文要向大家展示的C#多继承可能是大家闻所未闻见所未见的,甚至是发明C#语言的人也不曾想到我会这样去写代码,并且自得其乐. 说起多继承,首先大家可以想想这个 ...

  9. svn diff 详解

    UI版: 如果多人编辑同一段代码,常常容易出现冲突的情况: 如果出现冲突,我们如何解决他呢? 1 可以选择使用自己的文件mime file,也可以使用 他们的文件 their file 2 解决冲突, ...

  10. Win下最爱效率利器:AutoHotKey

    AutoHotkey是一个windows下的开源.免费.自动化软件工具.它由最初旨在提供键盘快捷键的脚本语言驱动(称为:热键),随着时间的推移演变成一个完整的脚本语言.但你不需要把它想得太深,你只需要 ...