• 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     }

  • 相关阅读:
    JavaScript 面向对象的编程(二) 类的封装
    js 防止重复提交表单
    JavaScript 面向对象的编程(一)
    layui laypage 当前页刷新问题
    jquery 选中设置的值
    突然觉得前端js挺不错的
    centos6.8 安装gitlab记录
    3/25/2018 学**况
    Threading、multiprocessing
    正则表达式 RegEx(Regular Expression)
  • 原文地址:https://www.cnblogs.com/javallh/p/9262879.html
Copyright © 2020-2023  润新知