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. vs11 微软下载地址

    https://www.microsoft.com/en-us/download/details.aspx?id=30679 vs11 微软的官方下载.最安全

  2. python笔记13-文件读写

    1.打开文件 f=open('a.txt','a+',encoding='utf-8')#f代表的是文件对象,叫句柄 f.seek(0)把文件指针到最前 文件打开模式有3种: 1:w写模式,它是不能读 ...

  3. 类的构造器-init和new

    提到构造器,大家都会想到 __init__,那么__new__是什么?也是构造器. init 构造器 都很熟悉了,直接上代码 class MyClass(object): def __init__(s ...

  4. effective java——30使用enum

    1, 枚举太阳系八大行星 package com.enum30.www; public enum Planet {//枚举太阳系八大行星 MERCURY(3.302e+23,2.439e6), VEN ...

  5. Java语法基础学习DayTwelve(泛型)

    一.泛型(Generic)在集合中的使用 1.作用 (1)解决元素存储的安全问题 (2)解决获取数据元素时,需要类型强转的问题 2.代码案例 //在集合没有使用泛型的情况下 List list = n ...

  6. Msfvenom学习总结

    1.    –p (- -payload-options) 添加载荷payload. 载荷这个东西比较多,这个软件就是根据对应的载荷payload生成对应平台下的后门,所以只有选对payload,再填 ...

  7. ubuntu 使用cron设置定时启动任务

    介绍 cron,是一个Linux定时执行工具,可以在无需人工干预的情况下运行作业. 在Ubuntu server 下,cron是被默认安装并启动的:如果没有启动,自行设置并启动(chkconfig\s ...

  8. More is better

    题目描述: Mr Wang wants some boys to help him with a project. Because the project is rather complex, the ...

  9. mpvue 转小程序实践总结

    介绍 Mpvue 是一个使用 Vue.js 开发小程序的前端框架.  基础介绍 框架基于 Vue.js 核心,修改了 Vue.js 的 runtime 和 compiler 实现,使其可以运行在小程序 ...

  10. dos语法

    一)MD——建立子目录 1.功能:创建新的子目录 2.类型:内部命令 3.格式:MD[盘符:][路径名]〈子目录名〉 4.使用说明: (1)“盘符”:指定要建立子目录的磁盘驱动器字母,若省略,则为当前 ...