zoukankan      html  css  js  c++  java
  • java并发编程CountDownLatch

     1 /**
     2      * CountDownLatch用法
     3      * CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。比如有一个任务A,
     4      * 它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了
     5      */
     6     @Test
     7     public void getThread(){
     8         final CountDownLatch latch = new CountDownLatch(2);
     9         new Thread (){
    10             @Override
    11             public void run() {
    12                 try {
    13                     System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
    14                     Thread.sleep(3000);
    15                     System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
    16                     latch.countDown();
    17                     System.out.println(latch);
    18                 }catch (InterruptedException e){
    19                     e.printStackTrace();
    20                 }
    21             }
    22         }.start();
    23         new Thread (){
    24             @Override
    25             public void run() {
    26                 try {
    27                     System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
    28                     Thread.sleep(3000);
    29                     System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
    30                     latch.countDown();
    31                     System.out.println(latch);
    32                 }catch (InterruptedException e){
    33                     e.printStackTrace();
    34                 }
    35             }
    36         }.start();
    37 
    38         try {
    39             System.out.println("等待2个子线程执行完毕...");
    40             latch.await();
    41             System.out.println("2个子线程已经执行完毕");
    42             System.out.println("继续执行主线程");
    43         }catch(InterruptedException e){
    44             e.printStackTrace();
    45         }
    46     }

  • 相关阅读:
    MongoDB安装&启动
    MongoDB集群搭建
    树与二叉树
    git入门
    MongoDB Java Driver
    Spring整合Junit4
    SQL字符串的数字部分递增
    [求职经历反面教材]4周面试20家,面霸磨成面瘫,仅供初级程序员参考!
    简陋的信息采集方式
    由一个博问学到的SQL查询方法 (一道多对多关系查询的面试题)
  • 原文地址:https://www.cnblogs.com/javallh/p/9262879.html
Copyright © 2011-2022 走看看