CountDownLatch是什么?
jdk1.5开始concurrent包里提供的,并发编程工具类。
CountDownLatch这个类能够使一个线程等待其他线程完成各自的工作后再执行。
CountDownLatch实现原理
CountDownLatch是通过一个计数器来实现的,计数器的初始值为线程的数量。每当一个线程完成了自己的任务后,计数器的值就会减1。当计数器值到达0时,它表示所有的线程已经完成了任务,然后在闭锁上等待的线程就可以恢复执行任务。
API
countDownLatch.countDown() //计数器递减1
countDownLatch.await();
使用示例:
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
long now = System.currentTimeMillis();
// CountDownLatch(2)总共有两个任务需要等待执行结果
CountDownLatch countDownLatch = new CountDownLatch(2);
Executor executor = Executors.newFixedThreadPool(3);
// 线程池里面的多个executor可以同时执行不同的task
executor.execute(new Task1(countDownLatch));
executor.execute(new Task2(countDownLatch));
countDownLatch.await(); //等待,等到了就打开门闩Latch
System.out.println("收工 cost:"+(System.currentTimeMillis()-now));
}
public static class Task1 implements Runnable{
private CountDownLatch countDownLatch;
public Task1(CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
Thread.sleep(3000);
System.out.println("做第一件事情");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(countDownLatch != null) {
countDownLatch.countDown();
}
}
}
}
public static class Task2 implements Runnable{
private CountDownLatch countDownLatch;
public Task2(CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
Thread.sleep(5000);
System.out.println("做第二件事情");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(countDownLatch != null) {
countDownLatch.countDown();
}
}
}
}
}
CountDownLatch底层原理
CountDownLatch通过AQS(AbstractQueuedSynchronizer)里面的共享锁来实现的。
ReentrantLock也是使用AQS