JAVA JUC CountDownLatch

 闭锁示例

class count implements Runnable{
    private CountDownLatch cdl;
    count(CountDownLatch cdl){
        this.cdl=cdl;
    }
    @Override
    public void run() {
        synchronized (this){
            try {
                for(int i=0;i<10000;i++){
                    if(i%2==0){
                        System.out.println(Thread.currentThread().getName()+"******"+i);
                    }
                }
            } finally {
                this.cdl.countDown();
            }
        }


    }
}
public class countDownLatchTest {
    public static void main(String[] args) {
        int threadNum =5;
        CountDownLatch cdl = new CountDownLatch(threadNum);
        count c = new count(cdl);
        long startT = System.currentTimeMillis();
        for(int i=0;i<threadNum;i++){
            new Thread(c).start();
        }
        long endT = System.currentTimeMillis();
        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("总计使用时"+(endT-startT));
    }
}
View Code
原文地址:https://www.cnblogs.com/superxuezhazha/p/12467751.html