java 多线程 2
1 package com.imooc.base; 2 3 public class Stage extends Thread { 4 5 public static void main(String[] args) { 6 new Stage().run(); 7 } 8 public void run(){ 9 10 System.out.println("欢迎观看隋唐演义!"); 11 12 try { 13 Thread.sleep(10000); 14 } catch (InterruptedException e1) { 15 e1.printStackTrace(); 16 } 17 18 System.out.println("大幕徐徐拉开"); 19 20 ArmyRunnable armyTaskOfSuiDynasty = new ArmyRunnable(); 21 ArmyRunnable armyTaskOfRevolt = new ArmyRunnable(); 22 23 Thread armyOfSuiDynasty = new Thread(armyTaskOfSuiDynasty,"隋军"); 24 Thread armyOfRevolt = new Thread(armyTaskOfRevolt,"农民起义军"); 25 26 armyOfSuiDynasty.start(); 27 armyOfRevolt.start(); 28 29 try { 30 Thread.sleep(50); 31 } catch (InterruptedException e) { 32 e.printStackTrace(); 33 } 34 35 armyTaskOfSuiDynasty.keepRunning = false; 36 armyTaskOfRevolt.keepRunning = false; 37 38 try { 39 armyOfRevolt.join(); 40 } catch (InterruptedException e) { 41 e.printStackTrace(); 42 } 43 44 System.out.println("正当双方激战正酣,半路杀出了个程咬金"); 45 46 Thread mrCheng = new KeyPersonThread(); 47 mrCheng.setName("程咬金"); 48 49 System.out.println("程咬金的理想就是结束战争,使百姓安居乐业!"); 50 51 armyTaskOfSuiDynasty.keepRunning = false; 52 armyTaskOfRevolt.keepRunning = false; 53 54 try { 55 Thread.sleep(2000); 56 } catch (InterruptedException e) { 57 e.printStackTrace(); 58 } 59 60 mrCheng.start(); 61 62 try { 63 mrCheng.join(); 64 } catch (InterruptedException e) { 65 e.printStackTrace(); 66 } 67 68 System.out.println("战争结束,人民安居乐业,程先生实现了自己的人生梦想!"); 69 System.out.println("谢谢观看"); 70 } 71 }
1 package com.imooc.base; 2 3 public class KeyPersonThread extends Thread { 4 public void run(){ 5 System.out.println(Thread.currentThread().getName()+"开始了战斗!"); 6 7 for(int i=0;i<10;i++){ 8 System.out.println(Thread.currentThread().getName()+"左突右杀,攻击隋军。。。"); 9 } 10 11 System.out.println(Thread.currentThread().getName()+"结束了战斗!"); 12 } 13 }
1 package com.imooc.base; 2 3 public class ArmyRunnable implements Runnable { 4 //volatile保证了线程可以正确的读取其他线程写入的值 5 //可见性 参考JMM,happens-before原则 6 volatile boolean keepRunning = true; 7 8 public void run() { 9 while(keepRunning){ 10 for(int i=0;i<5;i++){ 11 System.out.println(Thread.currentThread().getName()+"进攻方{"+ i +"}"); 12 13 Thread.yield(); 14 } 15 16 } 17 System.out.println(Thread.currentThread().getName()+"结束了战斗!"); 18 } 19 20 }