zoukankan      html  css  js  c++  java
  • CountDownLatch

    CountDownLatch

    在java.util.concurrent包下,它有类似计数器的功能,比如现有一个线程A,要等待其他3个线程执行完才执行,这时候可以用CountDownLatch来实现。

    构造器:

    CountDownLatch(int count) count为线程数

    方法:

    await() 调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行

    await(long timeout, TimeUnit unit) 和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行

    countDown() 将count值减1

    getCount() 获取当前的count

    例子:

     1 public class Test {
     2      public static void main(String[] args) {   
     3          final CountDownLatch latch = new CountDownLatch(2);
     4  
     5          new Thread(){
     6              public void run() {
     7                  try {
     8                      System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
     9                     Thread.sleep(3000);
    10                     System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
    11                     latch.countDown();
    12                 } catch (InterruptedException e) {
    13                     e.printStackTrace();
    14                 }
    15              };
    16          }.start();
    17  
    18          new Thread(){
    19              public void run() {
    20                  try {
    21                      System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
    22                      Thread.sleep(3000);
    23                      System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
    24                      latch.countDown();
    25                 } catch (InterruptedException e) {
    26                     e.printStackTrace();
    27                 }
    28              };
    29          }.start();
    30  
    31          try {
    32              System.out.println("等待2个子线程执行完毕...");
    33             latch.await();
    34             System.out.println("2个子线程已经执行完毕");
    35             System.out.println("继续执行主线程");
    36         } catch (InterruptedException e) {
    37             e.printStackTrace();
    38         }
    39      }
    40 }

    结果:

    线程Thread-0正在执行
    线程Thread-1正在执行
    等待2个子线程执行完毕...
    线程Thread-0执行完毕
    线程Thread-1执行完毕
    2个子线程已经执行完毕
    继续执行主线程
  • 相关阅读:
    SpringBoot与(Security)安全
    SpringBoot任务
    SSM框架整合思路
    数据库连接池 Druid和C3p0
    YAML语法:
    Mbatis使用
    为什么要使用Mybatis-现有持久化技术的对比
    SpringMVC拦截器
    ARC109D
    一类求斯坦纳树大小的问题
  • 原文地址:https://www.cnblogs.com/xc-chejj/p/10856723.html
Copyright © 2011-2022 走看看