1.概念
CountDownLatch是一个同步工具类,用来协调多个线程直接的同步。它能够使一个线程在等待另外一些线程完成各自的工作后,再继续执行。
2.实现原理
它是使用一个计数器实现的。计数器的初始值为线程的数量,当每一个线程执行完成后,计数器的值就会减一,当计数器的值为0的时候,表示所有的线程都已经执行完毕,然后在CountDownLatch上等待的线程就会恢复执行。
3.缺点
CountDownLatch是一次性的。计数器的值只能在构造方法中初始化一次,之后没有任何机制再次对其设置值。
4.用法
(1)一个线程等待所有的其它线程执行完任务之后自己再执行任务
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(3);
final Random random = new Random();
for(int i=0; i<3; i++){
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("一个线程执行完成");
latch.countDown();
}
}).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("所有线程执行完成");
}
(2)多个线程等待一个线程执行完成任务之后多个线程同时执行自己的任务
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(1);
final Random random = new Random();
for(int i=0; i<3; i++){
new Thread(new Runnable() {
public void run() {
try {
latch.await();
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("一个线程执行完成");
}
}).start();
}
latch.countDown();
System.out.println("主任务执行完成");
}