详解Java多线程与高并发(五)__CountDownLatch

匿名 (未验证) 提交于 2019-12-02 21:45:52

门闩 - CountDownLatch

可以和锁混合使用,或替代锁的功能。

理解:

门闩上挂了多把锁,在门闩未完全开放之前(门闩上还有锁)等待。当门闩完全开放后执行。

代码演示如下:

 public class Test_15 {          CountDownLatch latch = new CountDownLatch(5);    //初始化一个门闩,挂了5把锁                  void m1(){                 try {                         latch.await();// 等待门闩开放。                 } catch (InterruptedException e) {                         e.printStackTrace();                 }                 System.out.println("m1() method");         }         void m2(){                 for(int i = 0; i < 10; i++){                         if(latch.getCount() != 0){    // 门闩上还有锁                                 System.out.println("latch count : " + latch.getCount());                                 latch.countDown(); // 减门闩上的锁。                         }                         try {                                 TimeUnit.MILLISECONDS.sleep(500);                         } catch (InterruptedException e) {                                                                  e.printStackTrace();                         }                         System.out.println("m2() method : " + i);                 }         }         public static void main(String[] args) {                 final Test_15 t = new Test_15();                 new Thread(new Runnable() {                         @Override                         public void run() {                                 t.m1();                         }                 }).start();                 new Thread(new Runnable() {                         @Override                         public void run() {                                 t.m2();                         }                 }).start();         } } 

文章来源: https://blog.csdn.net/m0_37917271/article/details/92109134
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!