CountDownLatch是一个同步辅助类,可以使用它做一个类似于计数器的功能,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
典型的应用场景:
- 有一个任务想要往下执行,但必须要等到其他的任务执行完毕后才可以继续往下执行。
CountDownLatch类中最重要的三个方法。
public void await() throws InterruptedException { }; //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行 ### 初始值需要等待的事件的数量
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { }; //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行 就是过了超时时间后,就不再挂起等待,而是继续执行。
public void countDown() { }; //将count值减1 某一个事件在结束
例如:
import java.util.concurrent.CountDownLatch;
public class Test {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(2);
new Thread() {
public void run() {
try {
System.out.println("子任务" + Thread.currentThread().getName() + "正在进行");
Thread.sleep(2000);
System.out.println("子任务" + Thread.currentThread().getName() + "完成");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
;
}.start();
new Thread() {
public void run() {
try {
System.out.println("子任务" + Thread.currentThread().getName() + "正在进行");
Thread.sleep(2000);
System.out.println("子任务" + Thread.currentThread().getName() + "完成");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
;
}.start();
try {
System.out.println("等待2个子任务完成...");
latch.await();
System.out.println("2个子任务已经完成");
System.out.println("继续执行当前任务");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
等待2个子任务完成...
子任务Thread-0正在进行
子任务Thread-1正在进行
子任务Thread-0完成
子任务Thread-1完成
2个子任务已经完成
继续执行当前任务