CountDownLatch 闭锁
CountDownLatch 闭锁:在完成某些运算时,只有其他所有的运算全部完成,当前操作才会继续。
示例:计算一个多线程操作的耗时。
代码:
class LatchDemo implements Runnable {
private CountDownLatch latch;
//构造器
public LatchDemo(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
//打印50000 以内的偶数
for (int i = 0; i < 50000; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
}
main:
public class TestCountDownLatch {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(50);
LatchDemo ld = new LatchDemo(latch);
long start = System.currentTimeMillis();
for (int i = 0; i < 50; i++) {
new Thread(ld).start();
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
}
}
在不使用闭锁的情况下,main主线程会直接执行线程操作后的代码,这样不会得到我们想要的结果,无法计算多线程耗时。
使用闭锁:
public class TestCountDownLatch {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(50);
LatchDemo ld = new LatchDemo(latch);
long start = System.currentTimeMillis();
for (int i = 0; i < 50; 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() {
try {
for (int i = 0; i < 50000; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
} finally {
latch.countDown();
}
}
}
CountDownLatch latch = new CountDownLatch(50); 闭锁初始化,说明有50个线程在操作。
latch.await(); 让主线程等待,只有latch的锁为0,才继续往下走。
每个线程 操作完,使用 latch.countDown(); 将锁 减 1, 当 latch 的锁 为0的时候,主线程往下走。

浙公网安备 33010602011771号