前言
java.util.concurrent.CountDownLatch
类是一个并发构造,它允许许多一个或多个线程等待一系列指定操作的完成 CountDownLatch
以一个给定的数量初始化,countDown()
方法每调用一次,CountDownLatch
的数量就减一,通过调用await()
方法,线程可以阻塞等待这一数量到达零
创建一些类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class MaiGuo implements Runnable {
private CountDownLatch countDownLatch;
public MaiGuo(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { System.out.println("锅买完了"); countDownLatch.countDown(); } }
class MaiCai implements Runnable {
private CountDownLatch countDownLatch;
public MaiGuo(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } @Override public void run() { System.out.println("菜买完了"); countDownLatch.countDown(); } }
|
在主方法中创建并使用闭锁
<num>
:等待的线程的数量
1 2 3 4 5 6 7 8 9
| public static void main(String[] args) throws Exception { CountDownLatch countDownLatch = new CountDownLatch(<num>); new Thread(new MaiGuo(countDownLatch)).start(); new Thread(new MaiCai(countDownLatch)).start(); countDownLatch.await(); System.out.println("开始做菜"); }
|
完成