CountDownLatch闭锁使用

admin
2022-03-19 / 0 评论 / 187 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年03月19日,已超过979天没有更新,若内容或图片失效,请留言反馈。
import java.util.concurrent.CountDownLatch;

/**
 * @date: 2022/3/19 11:09
 * @version: 1.0
 */
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        myCountDownlatch myCountDownlatch = new myCountDownlatch(countDownLatch);
        long start = System.currentTimeMillis();
        for(int i=0;i<5;i++){
            new Thread(myCountDownlatch).start();
        }
        countDownLatch.await();

        long end = System.currentTimeMillis();

        System.out.println("耗时:"+(end-start));
    }

    public static class myCountDownlatch implements Runnable{
        private  CountDownLatch countDownLatch;

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

评论 (0)

取消