CountDownLatch

主要方法

 public CountDownLatch(int count);

 public void countDown();

 public void await() throws InterruptedException


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class CountDownLatchTest {

   
    public static void main(String[] args) throws InterruptedException {

     final  AtomicInteger  count = new AtomicInteger(0); //  用于计数选手是否准备就绪
     
        // 开始的倒数锁
        final CountDownLatch begin = new CountDownLatch(3);  

        // 结束的倒数锁
        final CountDownLatch end = new CountDownLatch(10);  

        // 十名选手
        final ExecutorService exec = Executors.newFixedThreadPool(10);  

        for (int index = 0; index < 10; index++) {
            final int NO = index + 1;  
            Runnable run = new Runnable() {
                public void run() {  
                    try {  
                        // 如果当前计数为零,则此方法立即返回。
                        // 等待
                      System.out.println("No." + NO + " has  be ready ! ");  
                      count.addAndGet(1);
                        begin.await();  
                        Thread.sleep((long) (Math.random() * 10000));  
                        System.out.println("No." + NO + " arrived");  
                    } catch (InterruptedException e) {  
                    } finally {  
                        // 每个选手到达终点时,end就减一
                        end.countDown();
                    }  
                }  
            };  
            exec.submit(run);
        }  
       
        while(count.get()<10){
        }
       
       
        for (int i = 1; i <= 3; i++) {
         Thread.sleep(1000);
         System.out.println("ready :" + i);
         begin.countDown();  
         if(i==3){
          break;
         }
   
  }
       
       
       
        System.out.println("Game Start");  
     // begin减一,开始游戏
     
       
        // 等待end变为0,即所有选手到达终点
        end.await();  
        System.out.println("Game Over");  
        exec.shutdown();  
    }
}

模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束

console:

No.2 has  be ready ! 
No.6 has  be ready ! 
No.8 has  be ready ! 
No.4 has  be ready ! 
No.1 has  be ready ! 
No.9 has  be ready ! 
No.5 has  be ready ! 
No.3 has  be ready ! 
No.7 has  be ready ! 
No.10 has  be ready ! 
ready :1
ready :2
ready :3
Game Start
No.6 arrived
No.10 arrived
No.4 arrived
No.3 arrived
No.5 arrived
No.7 arrived
No.2 arrived
No.8 arrived
No.9 arrived
No.1 arrived
Game Over







 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值