使用场景:

一个或N个线程,等待其它线程完成某项操作之后才能继续往下执行。CountDownLatch描述的是,一个或N个线程等待其他线程的关系。

使用方法:
  1. 设CountDownLatch个数:CountDownLatch countDownLatch=new CountDownLatch(3);
  2. 在等待线程中await:countDownLatch.await();
  3. 在其他线程中减少count值:countDownLatch.getCount();
  4. 一旦其他线程中的countDownLatch.getCount()的次数为实例化时的count值,就唤醒等待线程
public class T06_TestCountDownLatch {
public static void main(String[] args) {
usingJoin();
usingCountDownLatch();
} private static void usingCountDownLatch() {
Thread[] threads = new Thread[100];
CountDownLatch latch = new CountDownLatch(threads.length); for(int i=0; i<threads.length; i++) {
threads[i] = new Thread(()->{
int result = 0;
for(int j=0; j<10000; j++) result += j;
latch.countDown();
});
} for (int i = 0; i < threads.length; i++) {
threads[i].start();
} try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println("end latch");
} private static void usingJoin() {
Thread[] threads = new Thread[100]; for(int i=0; i<threads.length; i++) {
threads[i] = new Thread(()->{
int result = 0;
for(int j=0; j<10000; j++) result += j;
});
} for (int i = 0; i < threads.length; i++) {
threads[i].start();
} for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
} System.out.println("end join");
}
}

最新文章

  1. Xcode 6、7 打包
  2. [EWS]在exchange中的标识符
  3. Sublimetext (for windows)编译运行c出现Error 2错误的解决办法
  4. PDF合并
  5. Water Tree
  6. Autolayout-VFL语言添加约束-备
  7. Linux安装 Mysql
  8. 重新认识alias:通过alias让rm更安全
  9. (转)SQL中的循环、for循环、游标
  10. 【题解】魔板—洛谷P1275。
  11. https://finance.sina.com.cn/realstock/company/sh600522/nc.shtml
  12. 用Python进行有进度条的π计算
  13. iOS 在object-c 中调用c文件 方法
  14. 8 -- 深入使用Spring -- 0...
  15. 4 MySQL程序概述(包含mysql配置文件配置原理)-学习笔记
  16. 《剑指offer》— JavaScript(24)二叉树中和为某一值的路径
  17. input输出类型
  18. 深入理解redis复制原理
  19. CTSC/APIO2018 帝都一周游
  20. Model Binding is not working. MVC3 视图模型绑定不成功

热门文章

  1. Mysql实现定时清空一张表的旧数据并保留几条数据
  2. NET 调用人脸识别算法
  3. JVM笔记【1】-- 运行时数据区
  4. lambda表达式初识
  5. mysql源码分析-启动过程
  6. mysql The used table type doesn’t support FULLTEXT indexes 解决方案 (phpstudy 会出现),coten不会
  7. Debian9 升级至 Debian10
  8. Flutter 基础组件:单选框和复选框
  9. Sentry(v20.12.1) K8S 云原生架构探索,SENTRY FOR JAVASCRIPT Source Maps 详解
  10. MySQL 使用MD5对数据进行加密