1.当前线程等待其他线程执行完毕后在执行。

2.模拟高并发场景。

在多线程编程里,CountDownLatch是一个很好的计数器工具。

常用的两个方法:

1、计数器减一

public void countDown() {

sync.releaseShared(1);

}

2、线程等待,在计算器未到达0之前会一直等待

public void await() throws InterruptedException {

sync.acquireSharedInterruptibly(1);

}

好,下面来演示两个demo.

1、等待所有子线程执行完成后再执行主线程的情况

2、模拟高并发的情况

package com.figo.study.test;

import java.util.concurrent.CountDownLatch;

public class TestSomething {

public static void  main(String[] args) {

//testWaitThread();

testConcurrent();

        }

/**
* 1、模拟所有子线程都执行完成后再执行主线程
* countdownLatch计数,模拟子线程执行完成之后再执行主线程
* 这个也可以用future来实现

*/
public static void testWaitThread() { final CountDownLatch latch = new CountDownLatch(2); new Thread(){             public void run() {                 try {
                    System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
                   Thread.sleep(3000);
                   System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");                    latch.countDown();                } catch (InterruptedException e) {
                   e.printStackTrace();
               }
            };         }.start();         new Thread(){             public void run() {                 try {                     System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
                    Thread.sleep(3000);
                    System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
                    latch.countDown();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
            };         }.start();
        try {             System.out.println("等待2个子线程执行完毕...");            latch.await();            System.out.println("2个子线程已经执行完毕");            System.out.println("继续执行主线程");        } catch (InterruptedException e) {
           e.printStackTrace();
       }
} /**
     * 线程数量
     */     public static final int THREAD_NUM = 100;     /**
     * 开始时间
     */     private static long startTime = 0L;     /**
     * 2、模拟高并发
     */
public static void testConcurrent()
{
    try {
            startTime = System.currentTimeMillis();
            System.out.println("CountDownLatch started at: " + startTime);
            // 初始化计数器为1
            CountDownLatch countDownLatch = new CountDownLatch(1);
            for (int i = 0; i < THREAD_NUM; i ++) {
                new Thread(new Run(countDownLatch)).start();
            }
            // 启动多个线程
            countDownLatch.countDown();
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
} /**
     * 线程类
     */     private static class Run implements Runnable {         private final CountDownLatch startLatch;
        public Run(CountDownLatch startLatch) {
            this.startLatch = startLatch;
        }
        @Override
        public void run() {             try {
                // 线程等待
                startLatch.await();
                // 模拟耗时操作
                Thread.sleep(3000);
                long endTime = System.currentTimeMillis();
                System.out.println(Thread.currentThread().getName() + " ended at: " + endTime + ", cost: " + (endTime - startTime) + " ms.");             } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

CountDownLatch两种用法的更多相关文章

  1. c++ operator操作符的两种用法:重载和隐式类型转换,string转其他基本数据类型的简洁实现string_cast

    C++中的operator主要有两个作用,一是操作符的重载,一是自定义对象类型的隐式转换.对于操作符的重载,许多人都不陌生,但是估计不少人都不太熟悉operator的第二种用法,即自定义对象类型的隐式 ...

  2. operator 的两种用法

    C++,有时它的确是个耐玩的东东,就比如operator,它有两种用法,一种是operator overloading(操作符重载),一种是operator casting(操作隐式转换).1.操作符 ...

  3. Service的两种用法及其生命周期

    先来一点基础知识: Service 是android的四大组件之一,与Activity同属于一个级别,它是运行在后台进行服务的组件(例如在后台播放的音乐,播放音乐的同时并不影响其他操作).Servic ...

  4. JSP中的include的两种用法

    1.两种用法 <%@ include file=” ”%> <jsp:include page=” ” flush=”true”/> 2.用法区别 (1)执行时间上区别 < ...

  5. 子查询。ANY三种用法。ALL两种用法。HAVING中使用子查询。SELECT中使用子查询。

    子查询存在的意义是解决多表查询带来的性能问题. 子查询返回单行多列: ANY三种用法: ALL两种用法: HAVING中的子查询返回单行单列: SELECT中使用子查询:(了解就好,避免使用这种方法! ...

  6. Comparable和Comparator的区别&Collections.sort的两种用法

    在Java集合的学习中,我们明白了: 看到tree,可以按顺序进行排列,就要想到两个接口.Comparable(集合中元素实现这个接口,元素自身具备可比性),Comparator(比较器,传入容器构造 ...

  7. in有两种用法:

    # in有两种用法: 1. 在for中. 是把每一个元素获取到赋值给前⾯的变量. 2. 不在for中. 判断xxx是否出现在str中. #len() 为内置函数,输出为1,2,3,4....., 长度 ...

  8. [VC]C++ operator 两种用法

    C++中的operator,有两种用法,一种是operator overloading(操作符重载),一种是operator casting(操作隐式转换).下面分别进行介绍:   1.operato ...

  9. jsp中include的两种用法

    JSP中的include的两种用法 1.两种用法 <%@ include file=” ”%> <jsp:include page=” ” flush=”true”/> 2.用 ...

随机推荐

  1. 如何把已有SQLSERVER数据库更名而且附加到数据库中?

    如何把已有SQLSERVER数据库更名而且附加到数据库中? 例如:已有数据库:zrmaa,希望更名为jjsh 特别提醒:数据库名中不能加入下划线,因为数据库日志文件有下划线. 把数据库文件mdf和数据 ...

  2. sql中的limit关键字

    转载于:https://blog.csdn.net/benweizhu/article/details/7892788 一.基本 SQL的limit语法的如以下形式 SELECT * FROM tab ...

  3. BPM如何选型?

    Gartner 对BPM 的定义是:BPM 是一个描述一组服务和工具的一般名词,这些服务和工具为显式的流程管理(如流程的分析.定义.执行.监视和管理)提供支持. 不是所有的BPM 产品都能包括BPM ...

  4. postman操作练习用例

    1.注册用户:http://api.nnzhp.cn/api/user/user_reg 2.登录用户:http://api.nnzhp.cn/api/user/login 3.添加学生:http:/ ...

  5. C语言gcc处理过程

    gcc编译C文件一共四步,预处理(Preprocess),编译(Compilation),汇编(Assembly)和链接(Linking) 1. 预处理(Preprocess) 预处理是预处理中会展开 ...

  6. 剑指Offer 38. 二叉树的深度 (二叉树)

    题目描述 输入一棵二叉树,求该树的深度.从根结点到叶结点依次经过的结点(含根.叶结点)形成树的一条路径,最长路径的长度为树的深度. 题目地址 https://www.nowcoder.com/prac ...

  7. node 创建server 及加载静态页面

    1.Demo.js    创建Server let  http = require('http'); let url = require("url"); let util = re ...

  8. Semantic Compositionality through Recursive Matrix-Vector Spaces-paper

    Semantic Compositionality through Recursive Matrix-Vector Spaces 作者信息:Richard Socher Brody Huval Chr ...

  9. yii2 自带分页使用

    //下面为控制器层的方法内容use \yii\db\Query;use \yii\data\Pagination; //方法内容        $query=new Query();//from为自带 ...

  10. Opensource Licenses

    协议列表https://www.gnu.org/licenses/license-list.htmlhttps://opensource.org/licenses/alphabetical 协议选择参 ...