协调线程间同步的类之一------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();
        }
    }
}
相关文章
相关标签/搜索