@Test
public void test02() throws InterruptedException{
CountDownLatch cdl = new CountDownLatch(2); //new出CountDownLatch对象,初始指定线程数为2
new Thread(new BuyPot(cdl)).run();
new Thread(new BuyVege(cdl)).run(); //本次测试,只有两个线程都完成才能进行下一步
cdl.await(); //等待countDown为0时执行
System.out.println("cook dinner");
}
class BuyPot implements Runnable{
CountDownLatch cdl ;
public BuyPot(CountDownLatch cdl) {
this.cdl = cdl;
}
@Override
public void run() {
System.out.println("买锅");
cdl.countDown(); //买锅完成后countDown一次
}
}
class BuyVege implements Runnable{
CountDownLatch cdl ;
public BuyVege(CountDownLatch cdl) {
this.cdl = cdl;
}
@Override
public void run() {
System.out.println("买菜");
cdl.countDown(); //买菜完成后countDown一次
}
}
买锅
买菜
cook dinner