join方法作用
理解sleep带来的效果
关键人物的类
1 package cn.test.muke; 2 3 public class KeyPersonThread extends Thread { 4 5 public void run() { 6 7 System.out.println(Thread.currentThread().getName()+"开始了战斗!"); 8 9 for(int i = 0;i < 10;i++) { 10 11 System.out.println(Thread.currentThread().getName()+ "左突右杀,攻击隋军..."); 12 13 } 14 15 System.out.println(Thread.currentThread().getName()+"结束了战斗!"); 16 17 } 18 19 }
加入关键人物的stage。
1 package cn.test.muke; 2 /** 3 * 隋唐演义大戏舞台 4 * @author Tony Fan 5 * 6 */ 7 public class Stage extends Thread { 8 9 public void run() { 10 11 System.out.println("欢迎收看隋唐演义"); 12 13 try { 14 Thread.sleep(5000); 15 } catch (InterruptedException e1) { 16 // TODO Auto-generated catch block 17 e1.printStackTrace(); 18 } 19 20 System.out.println("大幕徐徐拉开"); 21 22 try { 23 Thread.sleep(5000); 24 } catch (InterruptedException e1) { 25 // TODO Auto-generated catch block 26 e1.printStackTrace(); 27 } 28 29 System.out.println("话说隋朝末年,隋朝军队与农民起义军杀得天昏地暗。。。"); 30 31 // 隋朝军队 32 ArmyRunnable armyTaskOfSuiDynasty = new ArmyRunnable(); 33 // 农民起义军 34 ArmyRunnable armyTaskOfRevolt = new ArmyRunnable(); 35 36 //使用Runnable接口创建线程 37 Thread armyOfSuiDynasty = new Thread(armyTaskOfSuiDynasty,"隋军"); 38 Thread armyOfRevolt = new Thread(armyTaskOfRevolt,"农民起义军"); 39 40 //启动线程,让军队开始作战 41 armyOfSuiDynasty.start(); 42 armyOfRevolt.start(); 43 44 45 //舞台线程休眠,大家专心观看均对厮杀 46 try { 47 Thread.sleep(50); 48 } catch (InterruptedException e) { 49 // TODO Auto-generated catch block 50 e.printStackTrace(); 51 } 52 53 54 System.out.println("正当双方激战正酣,半路杀出了个程咬金"); 55 56 Thread mrCheng = new KeyPersonThread(); 57 mrCheng.setName("程咬金"); 58 59 System.out.println("程咬金的理想就是结束战争,使百姓安居乐业"); 60 61 //军队停止作战 62 //停止线程的方法 63 armyTaskOfSuiDynasty.keepRunning = false; 64 armyTaskOfRevolt.keepRunning = false; 65 66 //此时可以使得军队完全停下来 67 try { 68 Thread.sleep(2000); 69 } catch (InterruptedException e) { 70 // TODO Auto-generated catch block 71 e.printStackTrace(); 72 } 73 74 /* 75 * 历史大戏留给关键人物 76 */ 77 mrCheng.start(); 78 79 //万众瞩目,所有线程等待程咬金完成历史使命 80 //join:等待当前进程结束,才会输出接下来的内容,使得程序按照代码顺序执行 81 try { 82 mrCheng.join(); 83 } catch (InterruptedException e) { 84 // TODO Auto-generated catch block 85 e.printStackTrace(); 86 } 87 88 89 System.out.println("战争结束,人民安居乐业!"); 90 System.out.println("谢谢关键隋唐演义,再见!"); 91 } 92 93 public static void main(String[] args) { 94 // TODO Auto-generated method stub 95 new Stage().start(); 96 97 } 98 99 }