对CountDownLatch的初步学习
CountDownLatch的中文翻译为"闭锁",在JDK1.5中 CountDownLatch类加入进来。为程序猿进行并发编程提供有利的帮助。
首先我们先看看JDK文档中对于CountDownLatch类的介绍:
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
大致意思是CountDownLatch为一个同步辅助工具,让一个或多个线程等待,直到其他的线程执行操作完成。
它的功能可以在绝大部分情况上替代join()方法,甚至在实际运用中比join()方法的用法更灵活。
操作过程:用CountDownLatch类创建实例,指定需要等待完成点个数。await()方法会阻塞当前线程,直到计数器减为零。每次线程执行调用countDown()方法,就会使计数器减1,直到计数器减为0时,等待的线程继续运行。
- CountDownLatch类中的构造器:
/**
* Constructs a {@code CountDownLatch} initialized with the given count.
*
* @param count the number of times {@link #countDown} must be invoked
* before threads can pass through {@link #await}
* @throws IllegalArgumentException if {@code count} is negative
* 构造器用给定计数作为参数进行初始化,若参数为负则抛出非法参数异常。
*
*/
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
- CountDownLatch类中的方法:
1. await() 方法
/**
* Causes the current thread to wait until the latch has counted down to
* zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
* 使当前线程等待直到闭锁的计数器为0,除非线程由于中断异常中断。
*/
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
2. await(long timeout, TimeUnit unit) 方法
/**
* Causes the current thread to wait until the latch has counted down to
* zero, unless the thread is {@linkplain Thread#interrupt interrupted},
* or the specified waiting time elapses.
* 使当前线程等待直到闭锁计数器为0,除非线程遇到线程中断异常中断,或者超出指定的等待时间。
* @param timeout the maximum time to wait 超出的最大等待时间
* @param unit the time unit of the {@code timeout} argument 指定最大等待时间的时间单位
* @return {@code true} if the count reached zero and {@code false}
* if the waiting time elapsed before the count reached zero
* @throws InterruptedException if the current thread is interrupted
* while waiting
*/
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
3. countDown() 方法
/**
* Decrements the count of the latch, releasing all waiting threads if
* the count reaches zero.
* 减少闭锁的计数,若计数达到0则释放所有等待线程
* <p>If the current count is greater than zero then it is decremented.
* If the new count is zero then all waiting threads are re-enabled for
* thread scheduling purposes.
*
* <p>If the current count equals zero then nothing happens.
*/
public void countDown() {
sync.releaseShared(1);
}
4. getCount() 方法
/**
* Returns the current count.
* 返回当前计数器的值
* <p>This method is typically used for debugging and testing purposes.
*
* @return the current count
*/
public long getCount() {
return sync.getCount();
}
应用:
有这么一道题:用4个线程并发执行从1加到100,每个线程只能加25个数,主线程需要等待子线程结束完成后才能结束。
思想:可以用join()方法,也可以用CountDownLatch对象来暂停主线程。
代码:
import java.util.concurrent.CountDownLatch;
public class Compute {
public static int sum = 0;// 存储1加到100的数
public static CountDownLatch count = new CountDownLatch(4);// 闭锁,计数器设置为4
static class ComputeThread extends Thread {// 内部类
int start, end;// 起始与结束
public ComputeThread(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {// 每个线程都进行累加
for (int i = start; i <= end; i++) {
sum += i;
}
System.out.println(currentThread().getName() + ":" + sum);
count.countDown();
}
}
public static void main(String[] args) throws InterruptedException {
// 建立4个线程
ComputeThread c1 = new Compute.ComputeThread(1, 25);
ComputeThread c2 = new Compute.ComputeThread(26, 50);
ComputeThread c3 = new Compute.ComputeThread(51, 75);
ComputeThread c4 = new Compute.ComputeThread(76, 100);
// 启动4个线程
c1.start();
c2.start();
c3.start();
c4.start();
// 让调用线程停止,等待计数器为0
count.await();
System.out.println(sum);
}
}
对CountDownLatch的初步学习的更多相关文章
- json2.js的初步学习与了解
json2.js的初步学习与了解,想要学习json的朋友可以参考下. json2.js的初步学习与了解 1.)该js的下载地址是:http://www.json.org/json2.js 2.)在页面 ...
- 老周的ABP框架系列教程 -》 一、框架理论初步学习
老周的ABP框架系列教程 -- 一.框架理论初步学习 1. ABP框架的来源与作用简介 1.1 简介 1.1.1 ABP框架全称为"ASP.NET Boilerplate ...
- 初步学习nodejs,业余用node写个一个自动创建目录和文件的小脚本,希望对需要的人有所帮助
初步学习nodejs,业余用node写个一个自动创建目录和文件的小脚本,希望对需要的人有所帮助,如果有bug或者更好的优化方案,也请批评与指正,谢谢,代码如下: var fs = require('f ...
- EF Codefirst 初步学习(二)—— 程序管理命令 更新数据库
前提:搭建成功codefirst相关代码,参见EF Codefirst 初步学习(一)--设置codefirst开发模式 具体需要注意点如下: 1.确保实体类库程序生成成功 2.确保实体表类库不缺少 ...
- 初步学习python
自计算机诞生以来,也伴随着计算机语言的诞生,现在,全世界的编程语言有600多种,但流行的编程语言也就20多种. Java和C一直占据着前两名.但是近年来伴随着人工智能的发展,Python发展迅猛,以其 ...
- Git的初步学习
前言 感谢! 承蒙关照~ Git的初步学习 为什么要用Git和Github呢?它们的出现是为了用于提交项目和存储项目的,是一种很方便的项目管理软件和网址地址. 接下来看看,一家公司的基本流程图: 集中 ...
- 语法分析器初步学习——LISP语法分析
语法分析器初步学习——LISP语法分析 本文参考自vczh的<如何手写语法分析器>. LISP的表达式是按照前缀的形式写的,比如(1+2)*(3+4)在LISP中会写成(*(+ 1 2)( ...
- 状态保持以及AJAX的初步学习
嘿嘿,今天学习的有点迷茫哦,主要学习把验证码使用在登录页面时间的一些逻辑,学习这个时间并没有那么的迷惑哦,可是自己写程序时间倒是有点反应迟钝,不过还好总是在最后搞清楚啦,另外就是一步一步的学习是接近项 ...
- LinQ的初步学习与总结
嘿嘿,说起来ORM和LinQ,就感觉离我好遥远的,在学校是没有学习的,所以总感觉学习了LinQ就是大神,现在嘛,终于也体会一点,感觉LinQ只是初步学习,没有太难,当然以后使用在项目中就没有这样的简单 ...
随机推荐
- C#操作Word Aspose.Words组件介绍及使用—基本介绍与DOM概述
1.基本介绍 Aspose.Words是一个商业.NET类库,可以使得应用程序处理大量的文件任务.Aspose.Words支持Doc,Docx,RTF,HTML,OpenDocument,PDF,XP ...
- [AWS] Deploy react project on EC2
如何在aws部署项目 申请到亚马逊AWS免费账户后,我们可以拥有很多的免费云服务产品项目,其中包括: EC2云服务器. Amazon S3存储. Amazon RDS数据库. Amazon Cloud ...
- HttpWatch的Result中出现Aborted的原因分析
我们在使用HttpWatch进行Web调试的过程中有时候会看到非HTTP Status Code(状态码)的值,例如:(Aborted). (Aborted)是HttpWatch中定义的三种非HTTP ...
- java面试(2)--大数据相关
第一部分.十道海量数据处理面试题 1.海量日志数据,提取出某日访问百度次数最多的那个IP. 首先是这一天,并且是访问百度的日志中的IP取出来,逐个写入到一个大文件中.注意到IP是32位的,最多有个2^ ...
- Android性能测试--内存
前言: 近阶段都在探索android性能测试方面的东西,其中一个很重要的指标就是内存.对于内存,主要是一些gc是不是及时,或者说一些引用有没有及时释放,有没有导致oom或者内存持续增加导致卡顿,有没有 ...
- linux下安装svn出现configure: error: We require OpenSSL; try --with-openssl
linux下安装svn出现configure: error: We require OpenSSL; try --with-openssl http://blog.csdn.net/woshixion ...
- 百度云曲显平:AIOps时代下如何用运维数据系统性地解决运维问题?
百度云智能运维负责人 曲显平 本文是根据百度云智能运维负责人曲显平10月20日在msup携手魅族.Flyme.百度云主办的第十三期魅族技术开放日<百度云智能运维实践>演讲中的分享内容整理而 ...
- vue项目打包后一片空白及资源引入的路径报错解决办法
网上很多说自己的VUE项目通过Webpack打包生成的list文件,放到HBulider打包后,通过手机打开一片空白.这个主要原因是路径的问题. 1.记得改一下config下面的index.js中bu ...
- [No0000DD]C# StringEx 扩展字符串类 类封装
using System; using System.Text.RegularExpressions; namespace Helpers { /// <summary> /// 包含常用 ...
- hdu6397 Character Encoding 母函数解约束条件下多重集
http://acm.hdu.edu.cn/showproblem.php?pid=6397 原问题的本质是问m个元素的多重集S,每一种类型的对象至多出现n-1次的S的k组合的个数是多少? 等价于 x ...