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源码!

最新文章

  1. 常见ES5方法
  2. thrift的lua实现
  3. 在ubuntu 14.04 64位添加32位库
  4. 什么是RST包,什么是三次握手,什么是四次握手 ---请进
  5. iOS 设置导航栏之二(设置导航栏的颜色、文字的颜色、左边按钮的文字及颜色)
  6. [Ubuntu] Error: The disk drive for /media/sda2 is not ready yet or not present
  7. mysql用户备份与修复
  8. jquery之css()改变字体大小,颜色,背景色
  9. 在TreeWidget中增加右键菜单功能 以及TreeWidget的基本用法
  10. 两句话帮你彻底记住gdb之eXamining memory
  11. 深入浅出Ajax(二)
  12. [NOI2011]阿狸的打字机(好题!!!!)
  13. 进程通信-SendMessage使用方法
  14. 第二章 ArrayList源码解析
  15. Unity制作即时战略游戏毕设
  16. android开发 写一个自定义形状的按键
  17. Manachar算法详解
  18. A problem has been detected and windows has been shut down to prevent damage
  19. Prism for WPF 搭建一个简单的模块化开发框架(六)隐藏菜单、导航
  20. vue 介绍的拓展

热门文章

  1. java8中lambda表达式的应用,以及一些泛型相关
  2. JavaScript中String对象的方法介绍
  3. Linux根文件系统分析之init和busybox
  4. 第14章 Linux启动管理(3)_系统修复模式
  5. Netty实现高性能RPC服务器优化篇之消息序列化
  6. 这可能是史上最全的CSS自适应布局总结教程
  7. 2000条你应知的WPF小姿势 基础篇&lt;45-50 Visual Tree&amp;Logic Tree 附带两个小工具&gt;
  8. ASP.NET MVC Model元数据(二)
  9. ABP(现代ASP.NET样板开发框架)系列之16、ABP应用层——数据传输对象(DTOs)
  10. 通过Gradle为APK瘦身