CountDownLatch闭锁
闭锁:延迟当前线程的进度,直到其他线程都执行完成当前线程才继续执行。
示例:计算多线程操作耗费时间
以下操作时无法正常计算多线程操作耗时的
package com.atguigu.juc;
public class TestCountDownLatch {
public static void main(String[] args) {
LatchDemo latchDemo = new LatchDemo();
long start = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
new Thread(latchDemo).start();
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
class LatchDemo implements Runnable{
@Override
public void run() {
for (int i = 0; i < 50000; i++) {
if (i % 2 == 0){
System.out.println(i);
}
}
}
}
使用闭锁改造为如下即可
package com.atguigu.juc;
import java.util.concurrent.CountDownLatch;
public class TestCountDownLatch {
public static void main(String[] args) {
// 这里的10要和线程个数一致
CountDownLatch countDownLatch = new CountDownLatch(10);
LatchDemo latchDemo = new LatchDemo(countDownLatch);
long start = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
new Thread(latchDemo).start();
}
try {
// countDownLatch的值为 0 时主线程会继续执行
countDownLatch.await();
} catch (InterruptedException e) {
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
}
}
class LatchDemo implements Runnable{
private CountDownLatch latch;
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();
}
}
}
}
注:汇总类的业务中可能会用到