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. Linux防火墙iptables的基础

    一.网络访问控制 1.Linux一般都是作为服务器系统使用,对外提供一些基于网络的服务 2.通常我们都需要对服务器进行一些网络访问控制,类似防火墙的功能 3.常见的访问控制包括:哪些IP可以访问服务器 ...

  2. sql整体优化的五种工具

    1.AWR报告 1.1 awr是什么? 它是关注于数据库整体性能状况,类比于我们去医院看病的体检报告,只是用一些指标对数据库做了一个判断. 1.2awr怎么获取 awr报告的获取有两种方式: 一.直接 ...

  3. powerdesigner(数据设计工具)

    https://jingyan.baidu.com/album/4f7d57120468c91a2019279f.html?picindex=1  (摘抄 原网地址)

  4. Android开发 ---基本UI组件7 :分页功能、适配器、滚动条监听事件

    效果图: 1.activity_main.xml 描述: 定义了一个按钮 <?xml version="1.0" encoding="utf-8"?> ...

  5. main函数

    class Main { public static void main(String[] args) //new String(0) { System.out.println(args); // [ ...

  6. Jquery 相关笔记

    //得到所有check var c = $(this).parent().find('input:checkbox'); if (c.is(':checked')) { var role = {}; ...

  7. 如何利用一台pc获取百万利益 《标题党》

    这是我在quora上看到的一个问题,我看到的被推荐的答案的第一句话就很nb. 有想法很容易做起来很难(不是这句) I’m going to give you something much more v ...

  8. FCC JS基础算法题(11):Seek and Destroy (摧毁数组)

    题目描述: 实现一个摧毁(destroyer)函数,第一个参数是待摧毁的数组,其余的参数是待摧毁的值. 我们可以使用arguments来进行参数的遍历. function destroyer(arr) ...

  9. grep、head和tail

    一.请给出打印test.txt内容时,不包含oldboy字符串的命令 Linux系统中grep命令是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹 配的行打印出来.grep全称是Globa ...

  10. JS的异步操作

    异步操作: 1.定时器都是异步操作 2.事件绑定都是异步操作 3.AJAX中一般我们都采用异步操作 4.回调函数可以理解为异步 同步:一次只能完成一个任务,如果多个任务就必须排队,先前面一个任务再执行 ...