CountDownLatch 闭锁
2016-06-06 14:39
381 查看
1.简述
从名字可以看出,CountDownLatch是一个倒数计数的锁, 当倒数到0时触发事件,也就是开锁,其他人就可以进入了。2.相关类
java.util.concurrent.CountDownLatch类。
java.util.concurrent.CountDownLatch.CountDownLatch(int count)
构造函数,设置计数器的初始值。
void java.util.concurrent.CountDownLatch.countDown()
每调用一次该方法,计数器减1。
void java.util.concurrent.CountDownLatch.await()
当前线程被阻塞,直到计数为0.
3.示例代码
package com.yichudu; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /* 下面的例子简单的说明了CountDownLatch的使用方法,模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。 */ public class CountDownLatchDemo { private static final int PLAY_AMOUNT = 10; public static void main(String[] args) { /* * 比赛开始:只要裁判说开始,那么所有跑步选手就可以开始跑了 */ CountDownLatch begin = new CountDownLatch(1); /* * 每个队员跑到末尾时,则报告一个到达,所有人员都到达时,则比赛结束 */ CountDownLatch end = new CountDownLatch(PLAY_AMOUNT); Player[] plays = new Player[PLAY_AMOUNT]; for (int i = 0; i < PLAY_AMOUNT; i++) { plays[i] = new Player(i + 1, begin, end); } ExecutorService exe = Executors.newFixedThreadPool(PLAY_AMOUNT); for (Player p : plays) {// 各就各位 exe.execute(p); } System.out.println("比赛开始"); begin.countDown();// 宣布开始 try { end.await();// 等待结束 } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.println("比赛结束"); } // 注意:此时main线程已经要结束了,但是exe线程如果不关闭是不会结束的 exe.shutdown(); } } class Player implements Runnable { private int id; private CountDownLatch begin; private CountDownLatch end; public Player(int id, CountDownLatch begin, CountDownLatch end) { super(); this.id = id; this.begin = begin; this.end = end; } public void run() { try { begin.await();// 必须等到裁判countdown到0的时候才开始 Thread.sleep((long) (Math.random() * 100));// 模拟跑步需要的时间 System.out.println("Play " + id + " has arrived. "); } catch (InterruptedException e) { e.printStackTrace(); } finally { end.countDown();// 向评委报告跑到终点了 } } } /* 比赛开始 Play 3 has arrived. Play 4 has arrived. Play 5 has arrived. Play 6 has arrived. Play 1 has arrived. Play 10 has arrived. Play 8 has arrived. Play 9 has arrived. Play 2 has arrived. Play 7 has arrived. 比赛结束 */
相关文章推荐
- 基于JS实现数字+字母+中文的混合排序方法
- C/C++ typedef用法
- 在eclipse如何删除无效的maven build
- -bash: ulimit: open files: cannot modify limit: Operation not permitted
- cxVerticalGrid1EditorRow
- Java是如何管理内存
- 全栈工程师
- fastjson
- Zabbix_Server安装
- Linux命令行下编辑文档
- 深入理解typedef
- 第12课第2.1节 字符设备驱动程序之LED驱动程序_编写编译
- maven jar包上传到服务器
- IOS中延时执行的几种方式的比较和汇总
- Python字符编码
- JavaScript 函数
- 有实物销售的传销行为应如何认定
- ios开源框架——如何在iOS SDK中创建一个umbrellaframework(framework库的再封装)
- Mysql优化相关总结
- Linux Rootkit 系列二:基于修改 sys_call_table 的系统调用挂钩