天天看點

詳解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();
        }
}
           

繼續閱讀