• 闭锁-CountDownLatch


    作用:用于一个或多个线程等待其它(一个或多个线程)完成相关操作.像日常生活的门锁一样,比如门装了三把锁,只有当三个把锁都打开时,门才能被打开.
    方法:
    CountDownLatch(int count)初始化闭锁,指定闩数量.
    await();等待通过锁,只有所有的闩都释放后,才能通过锁,阻塞当前线程.
    countDown();释放一个闩;
    //同 await(),这里指定一个等待超时时间,当到达指定的超时时间后,闩的数量没有减少到0,则返回 false,这里注意当前线程会阻塞指定的超时时间;
    //若在指定超时时间内,闩的数量减少到0,会立即返回 true.
    boolean await(long timeout, TimeUnit unit);
    long getCount();//获取闩的数量,主要用于调试
    实现原理:
    请参考抽象同步队列(AbstractQueuedSynchronizer)
    例子:
     
     1 public class CountDownLatchDemo {
     2 
     3     private static CountDownLatch countDownLatch=new CountDownLatch(100);
     4 
     5     private static int index=0;
     6     public static void main(String[] args) {
     7         try {
     8             for(int i=0;i<5;++i){
     9                 new Thread(){
    10                     @Override
    11                     public void run() {
    12                         try {
    13                             System.out.println("the thread "+Thread.currentThread().getId()+" pre entry the countdownlatch");
    14                             countDownLatch.await();
    15                             System.out.println("the thread "+Thread.currentThread().getId()+" pass the countdonwlatch!");
    16                         }catch (Throwable throwable){
    17                             throwable.printStackTrace();
    18                         }
    19                     }
    20                 }.start();
    21             }
    22             while (index++<100) {
    23                 new Thread() {
    24                     @Override
    25                     public void run() {
    26                         try {
    27                             Thread.sleep(100);
    28                         } catch (Throwable throwable) {
    29                             throwable.printStackTrace();
    30                         }
    31 
    32                         System.out.println("countdown of thread " + Thread.currentThread().getId());
    33                         countDownLatch.countDown();
    34                     }
    35                 }.start();
    36             }
    37             System.in.read();
    38         }catch (Throwable throwable){
    39             throwable.printStackTrace();
    40         }
    41 
    42 
    43     }
    44 }
    View Code
  • 相关阅读:
    K8S实战(十七)| 通过 StorageClass 实现动态卷供应
    K8S实战(十六)| 持久化存储卷
    K8S实战(十五)| 存储卷概念
    K8S实战(十四)| ConfigMap 对象
    K8S实战(十三)| Secret 对象
    K8S实战(十二)| 为 Ingress 以及后端 Nginx 增加证书
    批量删除git 本地分支、远程分支、tag
    React 页面间传值的个人总结
    搭建一个属于自己的webpack config(-)
    HTTP 2 新特性
  • 原文地址:https://www.cnblogs.com/hhbk/p/7735516.html
Copyright © 2020-2023  润新知