美文网首页
CountDownLatch门闩

CountDownLatch门闩

作者: yongguang423 | 来源:发表于2018-05-04 12:28 被阅读9次

    门闩是concurrent包中定义的一个类型,是用于多线程通讯的一个辅助类型。
    门闩相当于在一个门上加多个锁,当线程调用await方法时,会检查门闩数量,如果门
    闩数量大于0,线程会阻塞等待。当线程调用countDown时,会递减门闩的数量,当门闩数量为0时,await阻塞线程可执行。

    /**
     * CountDownLatch 门闩
     */
    package com.sxt.concurrent.t02;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.CyclicBarrier;
    import java.util.concurrent.Semaphore;
    import java.util.concurrent.TimeUnit;
    
    public class Test_03 {
        public static void main(String[] args) {
            final Test_03_Container t = new Test_03_Container();
            final CountDownLatch latch = new CountDownLatch(1);
    
            new Thread(new Runnable(){
                @Override
                public void run() {
                    if(t.size() != 5){
                        try {
                            latch.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("size = 5");
                }
            }).start();
            
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for(int i = 0; i < 10; i++){
                        System.out.println("add Object to Container " + i);
                        t.add(new Object());
                        if(t.size() == 5){
                            latch.countDown();
                        }
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }
    
    class Test_03_Container{
        volatile List<Object> container = new ArrayList<>();
        
        public void add(Object o){
            this.container.add(o);
        }
        
        public int size(){
            return this.container.size();
        }
    }
    

    相关文章

      网友评论

          本文标题:CountDownLatch门闩

          本文链接:https://www.haomeiwen.com/subject/lprdrftx.html