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. BPM费控管理解决方案分享

    一.方案概述费用是除经营成本外企业的最主要支出,费用管理是财务管理的核心之一,加强企业内控管理如:费用申请.费用报销.费用分摊.费用审批.费用控制和费用支付等,通过科学有效的管理方法规范企业费用管理, ...

  2. GSD_WeiXin(高仿微信)应用源码

    高仿微信计划:已经实现功能 1.微信首页(cell侧滑编辑.下拉眼睛动画.下拉拍短视频.点击进入聊天详情界面) 2.通讯录(联系人字母排序.搜索界面) 3.发现(朋友圈) 4.我(界面) 待实现功能( ...

  3. CYQ.Data V5 从入门到放弃ORM系列:教程 - MAction类使用

    背景: 随着V5框架使用者的快速增加,终于促使我开始对整个框架编写完整的Demo. 上周大概花了一星期的时间,每天写到夜里3点半,终完成了框架所有功能的Demo. 同时,按V5框架名称空间的顺序,对每 ...

  4. Vue.js——60分钟browserify项目模板快速入门

    概述 在之前的一系列vue.js文章,我们都是用传统模式引用vue.js以及其他的js文件的,这在开发时会产生一些问题. 首先,这限定了我们的开发模式是基于页面的,而不是基于组件的,组件的所有代码都直 ...

  5. 前端构建大法 Gulp 系列 (三):gulp的4个API 让你成为gulp专家

    系列目录 前端构建大法 Gulp 系列 (一):为什么需要前端构建 前端构建大法 Gulp 系列 (二):为什么选择gulp 前端构建大法 Gulp 系列 (三):gulp的4个API 让你成为gul ...

  6. iOS开发系列--数据存取

    概览 在iOS开发中数据存储的方式可以归纳为两类:一类是存储为文件,另一类是存储到数据库.例如前面IOS开发系列-Objective-C之Foundation框架的文章中提到归档.plist文件存储, ...

  7. MVC中的AOP

    一. AOP是什么? AOP(Aspect-Oriented Programming),面向切面编程,看着是跟OOP(面向对象编程)挺相近的,但实际上又有什么区别呢?OOP具有封装,继承,多态等东西来 ...

  8. 【Win 10应用开发】延迟共享

    延迟共享是啥呢,这么说吧,就是在应用程序打开共享面板选择共享目标时,不会设置要共享的数据,而是等到共享目标请求数据时,才会发送数据,而且,延迟操作可以在后台进行. 这样说似乎过于抽象,最好的诠释方法, ...

  9. 多线程条件通行工具——Semaphore

    Semaphore的作用是,限制线程通行的数量,如果线程进入时达到通行数量,便等待其它正在通行的线程释放. acquire()获取通行 release()释放通行 availablePermits() ...

  10. 增强学习(二)----- 马尔可夫决策过程MDP

    1. 马尔可夫模型的几类子模型 大家应该还记得马尔科夫链(Markov Chain),了解机器学习的也都知道隐马尔可夫模型(Hidden Markov Model,HMM).它们具有的一个共同性质就是 ...