JUC-5-CountDownLatch 闭锁

package com.wf.zhang.juc;

import java.util.concurrent.CountDownLatch;

/**
* CountDownLatch 闭锁 同步辅助类
* 一组操作中,多个线程完成, 闭锁会允许一个或多个线程一直等待.
* 即 所有线程都完成才继续执行
*
* 场景:5个线程 打印50000以内的偶数 所用的时间
*
* 相当于每个线程都有一个倒计时器 (这里都是5个,5个线程5个倒计时器) 所有倒计时都归零是才执行计算时间
*/
public class TestCountDownLatch {

public static void main(String[] args) {

final CountDownLatch latch = new CountDownLatch(5);
LatchDemo ld = new LatchDemo(latch);

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

try {
//等待所有线程都执行完
latch.await();
} catch (InterruptedException e) {
}

long end = System.currentTimeMillis();
System.out.println("耗费时间为: " + (end - start));
}
}

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 < 50000; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
} finally {
//计数-1
latch.countDown();
}
}
}
}
上一篇:并发测试->countDownLatch


下一篇:CountDownLatch(倒计时计数器)使用说明