package?com.currentcount.base;
/**
?*?搭建了舞臺線程
?*?
?*
?*/
public?class?Stage?extends?Thread?{
//復寫run方法
public?void?run(){
System.out.println("歡迎觀看隋唐演義!");
try?{
Thread.sleep(5000);
}?catch?(InterruptedException?e2)?{
e2.printStackTrace();
}
System.out.println("大幕徐徐拉開");
try?{
Thread.sleep(5000);
}?catch?(InterruptedException?e2)?{
//?TODO?Auto-generated?catch?block
e2.printStackTrace();
}
System.out.println("話說隋朝末年,各路藩王和隋軍殺的是昏天黑地");
ArmyRunnable?armyTaskOfSuiDynasty=new?ArmyRunnable();
ArmyRunnable?armyTaskOfFarmer=new?ArmyRunnable();
//使用Runnable創建線程
Thread?armyOfSuiDynasty=new?Thread(armyTaskOfSuiDynasty,"隋朝軍隊");
Thread?armyOfFarmer=new?Thread(armyTaskOfFarmer,"農民軍隊");
//線程的運行
armyOfSuiDynasty.start();
armyOfFarmer.start();
//讓舞臺線程休眠,大家能夠專心觀看軍隊的廝殺
try?{
Thread.sleep(50);
}?catch?(InterruptedException?e)?{
e.printStackTrace();}
try?{
armyOfFarmer.join();
}?catch?(InterruptedException?e1)?{
e1.printStackTrace();
}
System.out.println("正當雙方激戰正酣,半路殺出了個程咬金");
Thread?Chengyaojin=new?KeypersonThread();
Chengyaojin.setName("程咬金");
System.out.println("程咬金的理想就是結束戰斗,使得百姓安居樂業");
//軍隊停止戰斗
armyTaskOfSuiDynasty.keepRunning=false;
armyTaskOfFarmer.keepRunning=false;
try?{
Thread.sleep(2000);
}?catch?(InterruptedException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
Chengyaojin.start();
//所有線程等待程咬金完成自己的歷史使命
try?{
Chengyaojin.join();
}?catch?(InterruptedException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
System.out.println("程咬金完成了自己的理想,結束了戰斗,使得人民能夠安居樂業");
System.out.println("感謝觀看隋唐演義!");
}
2015-12-18
Stage的run方法里有armyOfFarmer.join();這句。這句的意思是說農民的run方法執行完了才能往armyOfFarmer.join();這句代碼之后運行。但你看看你的ArmyRunnable的run方法里,while?(keepRunning)的keepRuning一直是true,while循環沒有被終止。所以發生了死鎖。
把Stage的run方法里的armyTaskOfFarmer.keepRunning=false;這句代碼修改到armyOfFarmer.join();這句代碼之前,就不會發生死鎖了。
下面是我修改之后的代碼
2015-12-18
2015-12-18
沒注意還有個這個KeypersonThread...這個里面是什么啊
2015-12-18
2015-12-18
ArmyRunnable這個Runnable里面寫的是什么啊