天天看点

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

门闩 - 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();
        }
}
           

继续阅读