greenhandc
2015-12-18 10:18
public class ArmyRunnable implements Runnable { //这里使用volatile保证线程可以正确的读取其他线程写入的值 volatile boolean keepRunning=true ; //军队线程 //用来模拟作战 public void run() { while (keepRunning){ //发动五连击 for(int i=0;i<5;i++){ System.out.println(Thread.currentThread().getName()+"进攻"+i+"次"); //让出处理器的时间,下次谁攻击还不一定 Thread.yield(); } } System.out.println(Thread.currentThread().getName()+"停止攻击"); } } public class Stage extends Thread { //复写run方法 public void run(){ 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(); armyTaskOfSuiDynasty.keepRunning=false; armyTaskOfFarmer.keepRunning=false; try { armyOfFarmer.join(); } catch (InterruptedException e1) { e1.printStackTrace(); } } } public static void main(String []args){ new Stage().start(); } } 这个程序运行起来是个死循环啊
噢。找到错误了!不小心把
armyTaskOfSuiDynasty.keepRunning=false;
armyTaskOfFarmer.keepRunning=false;
这两句弄到try Catch中去了
深入浅出Java多线程
186088 学习 · 464 问题
相似问题