目录
写在哪个线程体,当前线程体就被阻塞

故事理解join
package com.pt.thread;
/**
* 理解join
* @author tyler
*
*/
public class Join {
public static void main(String[] args) {
System.out.println("猪儿和儿子买酱油的故事");
new Thread(new Piggy()).start();
}
}
class Piggy extends Thread{
public void run() {
super.run();
System.out.println("猪儿想炒一个酱肉丝,发现没酱油了");
System.out.println("让儿子去买海天酱油");
// 儿子出现
Thread thread = new Thread(new Son());
thread.start();
// 需要等待,才能执行下面的操作
try {
thread.join(); // 当前线程被阻塞
System.out.println("猪儿接过酱油,得知儿子扶了老奶奶,表扬儿子,剩下零钱给了儿子");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("儿子太久不回来,猪儿去找儿子");
}
}
}
class Son extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
System.out.println("儿子接过猪儿的钱出去了");
System.out.println("路边有个老奶奶过马路,儿子去扶老奶奶");
for (int i = 1; i < 11; i++) {
System.out.println(i + "分钟过去了");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("扶完了老奶奶,该去打酱油了。。。");
System.out.println("买好酱油,回家!");
}
}
运行结果
猪儿和儿子买酱油的故事
猪儿想炒一个酱肉丝,发现没酱油了
让儿子去买海天酱油
儿子接过猪儿的钱出去了
路边有个老奶奶过马路,儿子去扶老奶奶
1分钟过去了
2分钟过去了
3分钟过去了
4分钟过去了
5分钟过去了
6分钟过去了
7分钟过去了
8分钟过去了
9分钟过去了
10分钟过去了
扶完了老奶奶,该去打酱油了。。。
买好酱油,回家!
猪儿接过酱油,得知儿子扶了老奶奶,表扬儿子,剩下零钱给了儿子
585

被折叠的 条评论
为什么被折叠?



