在现实生活中,经常发生这样的场景,即有两件事情A和B,事情A的结束需要等待B完成之后,这时如果A在B还没完成之前就开始,就必须要做等待工作。
在Java语言中如果想让某个线程等待另一个线程运行完后才继续运行,就需要用到类Thread的join()方法。
下面讲解如何通过线程模拟做饭的场景的实例外,还将详细讲解线程的join方法
儿子的类
public class Son implements Runnable { //实现Runnable接口
public void run() { //实现方法run()
//输出相应的信息,即儿子开始出去买酱油
System.out.println("儿子出门去买酱油");
System.out.println("儿子买东西来回需5分钟");
//买酱油的过程
try {
for (int i = 1; i <= 5; i++) {
Thread.sleep(1000); //线程休眠
System.out.print(i + "分钟 "); //输出相应的时间
}
} catch (InterruptedException ie) {
System.err.println("儿子发生意外"); //买酱油失败
}
System.out.println("\n儿子买酱油回来了"); //买酱油回到家
}
}
妈妈的类
public class Mother implements Runnable
{
public void run()
{
System.out.println("妈妈准备煮饭");
System.out.println("妈妈发现酱油用完了");
System.out.println("妈妈叫儿子去买酱油");
Thread son = new Thread(new Son());
son.start();
System.out.println("妈妈等待儿子把酱油买回来");
try {
son.join();
}
catch (InterruptedException ie)
{
System.err.println("发生异常!");
System.err.println("妈妈中断煮饭");
System.exit(1);
}
System.out.println("妈妈开始煮饭");
System.out.println("妈妈煮好饭了");
}
}
做房场景的类
public class Cooking
{
public static void main(String argv[])
{
Thread mother = new Thread(new Mother());
mother.start();
}
}
上述的运行结果可以发现不能模拟正常的做饭场景,因为妈妈还没等儿子把酱油买回来就把饭做好了。