cocurrent包countdownlatch 倒计时门栓

编程入门 行业动态 更新时间:2024-10-06 22:20:25

cocurrent包countdownlatch <a href=https://www.elefans.com/category/jswz/34/1769463.html style=倒计时门栓"/>

cocurrent包countdownlatch 倒计时门栓

latch 英[lætʃ]
美[lætʃ]
n. 门闩; 弹簧锁;

 

锁是每个类的成员变量,它是这个类的固有属性,当然要声明为成员变量。

成员变量的初始化是通过对象的构造函数的。

锁是每个类的成员变量,它是这个类的固有属性,当然要声明为成员变量。

成员变量的初始化是通过对象的构造函数的。

 

锁是每个类的成员变量,它是这个类的固有属性,当然要声明为成员变量。

成员变量的初始化是通过对象的构造函数的。

 

12. 闭锁 CountDownLatch

java.util.concurrent.CountDownLatch 是一个并发构造,它允许一个或多个线程等待一系列指定操作的完成。
CountDownLatch 以一个给定的数量初始化。countDown() 每被调用一次,这一数量就减一。通过调用 await() 方法之一,线程可以阻塞等待这一数量到达零。

CountDownLatch 以一个给定的数量初始化。countDown() 每被调用一次,这一数量就减一。通过调用 await() 方法之一,线程可以阻塞等待这一数量到达零。
以下是一个简单示例。Decrementer 三次调用 countDown() 之后,等待中的 Waiter 才会从 await() 调用中释放出来。

[java]  view plain copy
    1. CountDownLatch latch = new CountDownLatch(3);  
    2.   
    3. Waiter      waiter      = new Waiter(latch);  
    4. Decrementer decrementer = new Decrementer(latch);  
    5.   
    6. new Thread(waiter)     .start();  
    7. new Thread(decrementer).start();  
    8.   
    9. Thread.sleep(4000);  
    10.   
    11. public class Waiter implements Runnable{  
    12.   
    13.     CountDownLatch latch = null;  
    14.   
    15.     public Waiter(CountDownLatch latch) {  
    16.         this.latch = latch;  
    17.     }  
    18.   
    19.     public void run() {  
    20.         try {  
    21.             latch.await();  
    22.         } catch (InterruptedException e) {  
    23.             e.printStackTrace();  
    24.         }  
    25.   
    26.         System.out.println("Waiter Released");  
    27.     }  
    28. }  
    29.   
    30. public class Decrementer implements Runnable {  
    31.   
    32.     CountDownLatch latch = null;  
    33.   
    34.     public Decrementer(CountDownLatch latch) {  
    35.         this.latch = latch;  
    36.     }  
    37.   
    38.     public void run() {  
    39.   
    40.         try {  
    41.             Thread.sleep(1000);  
    42.             this.latch.countDown();  
    43.   
    44.             Thread.sleep(1000);  
    45.             this.latch.countDown();  
    46.   
    47.             Thread.sleep(1000);  
    48.             this.latch.countDown();  
    49.         } catch (InterruptedException e) {  
    50.             e.printStackTrace();  
    51.         }  
    52.     }  
    53. }   

转载于:.html

更多推荐

cocurrent包countdownlatch 倒计时门栓

本文发布于:2024-02-27 22:13:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1766639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:倒计时   cocurrent   countdownlatch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!