JUC--閉鎖 CountDownLatch

CountDownLatch是一個同步輔助類,在完成一組正在其餘線程中執行的操做以前,容許一個或者多個線程一直等待。ide

閉鎖能夠延遲線程的進度直到其到達終止狀態,能夠確保某些活動知道其餘活動都完成才繼續執行this

 

 

注意:在run方法中必須將調用countdown方法 計數減1 而且在new CountDownLatch時建立的個數要和for循環中的線程個數相等,而且調用latch.await()方法進行等到全部的thread執行完畢。spa

 

應用場景:線程

  例如 超市中多個線程計算每一個種類的商品的信息 ,使用countdownlatch等到各個種類的信息計算完以後,統計總信息。code

 

/**
 * countdownlatch 閉鎖 在完成某些運算時,只有其餘全部thread得運算所有完成 當前運算才能繼續執行
 */
public class TestCountDownLatch {
    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(5);
        CDLDemo ld= new CDLDemo(latch);
        long start =System.currentTimeMillis();
        for(int i=0;i<5;i++){
            new Thread(ld).start();
        }
        try{
            latch.await();
        }catch (InterruptedException e){
        }
        long end = System.currentTimeMillis();
        System.out.println("use time:================"+(end-start));
    }
}

class CDLDemo implements Runnable {
    private CountDownLatch latch;
     CDLDemo(CountDownLatch latch) {
        this.latch = latch;
    }




    @Override
    public void run() {
        synchronized (this){
            try{
                for(int i=0;i<500;i++){
                    if(i%2==0)
                        System.out.println(i);
                }
            }finally {

                latch.countDown();
            }

        }



    }
}
相關文章
相關標籤/搜索