協調線程間同步的類之一------CountDownLatch學習筆記

一。java

    1>CountDownLatch簡介ide

        CountDownLatch是一個計數器,它有一個初始數,等待這個計數器的線程必須等到計數器數到0時才能夠執行、測試

         和join方法有類似之處
this

    2>測試代碼以下。重點在被註釋那兩行,比較註釋與否的差異就明白其做用了
線程

public class CountDownLatchTest {
    public static class ComponentThread implements Runnable{
        CountDownLatch latch;
        int ID;
        public ComponentThread(CountDownLatch latch,int id){
            this.latch=latch;
            this.ID=id;
        }
        @Override
        public void run() {
            System.out.println("initializing component"+ID);
            try {
                Thread.sleep(ID*2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("component "+ID+" initialed");
            latch.countDown();
        }
    }
    public static void startServer() throws Exception{
        System.out.println("server starting");
        CountDownLatch latch=new CountDownLatch(3);
        ExecutorService service=Executors.newCachedThreadPool();
        service.submit(new ComponentThread(latch, 1));
        service.submit(new ComponentThread(latch, 2));
//        service.submit(new ComponentThread(latch, 3));
        service.shutdown();
//        latch.await();
        System.out.println("servier is up");
    }
    public static void main(String[] args) {
        try {
            startServer();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
相關文章
相關標籤/搜索