标签:name pad ring out generate ted 含义 结果 stat
今天回想线程方面的知识,发现一个非常有意思的小程序。是用来说明多线程的以下贴出来分享下,对刚開始学习的人理解线程有非常大的帮助
爸爸和儿子的故事
<span style="font-family:KaiTi_GB2312;font-size:18px;">public class FatherThread extends Thread{
@Override
public void run() {
System.out.println("爸爸想抽烟。发现烟抽完了");
System.out.println("爸爸让儿子去买包红塔山");
Thread son = new SonThread();
son.start();
System.out.println("爸爸等儿子买烟回来");
try {
//join含义:等待son线程运行完成,father线程才继续运行
son.join();
}
catch (InterruptedException e) {
System.out.println("爸爸出门去找儿子跑哪去了");
System.exit(1);
}
System.out.println("爸爸高兴的接过烟開始抽,并把零钱给了儿子");
}
} </span><span style="font-family:KaiTi_GB2312;font-size:18px;">public class SonThread extends Thread{
@Override
public void run() {
String tags ="\t\t\t\t\t";
System.out.println(tags+"儿子去买烟了");
System.out.println(tags+"儿子去买烟要10分钟");
try {
for(int i =0; i<10;){
Thread.sleep(1000);
System.out.println(tags+"儿子出去第"+ ++i +"分钟");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(tags+"儿子去买烟回来了");
}
} </span><span style="font-family:KaiTi_GB2312;font-size:18px;">public class Main {
public static void main(String[] args){
System.out.println("爸爸和儿子的故事");
Thread faThread =new FatherThread();
faThread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} </span>标签:name pad ring out generate ted 含义 结果 stat
原文地址:http://www.cnblogs.com/yfceshi/p/7136322.html