CountDownLatch 闭锁

2018-03-11  本文已影响39人  zheting

下面的代码实现了主线程等待子线程完成,计算子线程执行的时间

package com.sheting.concurrent.countDownLatchDemo;

import java.util.concurrent.CountDownLatch;

/**
 * Create Time: 2018-03-09 10:13
 *
 * @author sheting
 */
public class TestCountDownLatch {

    public static void main(String[] args) {
        //初始值为5 要和 等待的线程数量保持一致
        CountDownLatch countDownLatch = new CountDownLatch(5);
        LatchDemo latchDemo = new LatchDemo(countDownLatch);

        long startTime = System.currentTimeMillis();
        for (int i = 0; i <5 ; i++) {
            new Thread(latchDemo).start();
        }

        try {
            //等待线程执行完成,也就是是初始值5变为0
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println(String.format("cost time:%sms",  (endTime - startTime)));

    }
}

class LatchDemo implements Runnable{
    private CountDownLatch latch;

    public LatchDemo(CountDownLatch latch){
        this.latch = latch;
    }

    @Override
    public void run() {
        synchronized (this){
            try {
                for (int i = 0; i <5000 ; i++) {
                    if(i%2 == 0){
                        System.out.println(i);
                    }
                }
            }finally {
                //每次递减一
                latch.countDown();
            }
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读