每天起早贪黑的上班,父母每天也要上班,话说今天定了个饭店,一家人一起吃个饭,通知大家下班去饭店集合。假设:3个人在不同的地方上班,必须等到3个人到场才能吃饭,用程序如何实现呢?
代码如下:
package com.qimh.concurrent;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
/**
* 模拟爸爸去饭店
*/
public static void fatherToRes()
{
System.out.println("爸爸步行去饭店需要3小时。");
}
/**
* 模拟我去饭店
*/
public static void motherToRes()
{
System.out.println("妈妈挤公交去饭店需要2小时。");
}
/**
* 模拟妈妈去饭店
*/
public static void meToRes()
{
System.out.println("我乘地铁去饭店需要1小时。");
}
/**
* 模拟一家人到齐了
*/
public static void togetherToEat()
{
System.out.println("一家人到齐了,开始吃饭");
}
private static CountDownLatch latch = new CountDownLatch(3);
public static void main(String[] args) throws InterruptedException
{
new Thread()
{
public void run()
{
fatherToRes();
latch.countDown();
};
}.start();
new Thread()
{
public void run()
{
motherToRes();
latch.countDown();
};
}.start();
new Thread()
{
public void run()
{
meToRes();
latch.countDown();
};
}.start();
latch.await();
togetherToEat();
}
}
参考案例:https://blog.csdn.net/lmj623565791/article/details/26626391