/** * 軍隊線程 * 模擬做戰雙方的行爲 * @author gent * */ public class ArmyRunnable implements Runnable{ //volatile保證了線程能夠正確讀取其餘線程寫入的值 //可見性 ref JMM,happens-before原則 volatile boolean keepRunning = true; @Override public void run() { while (keepRunning) { //發動5連擊 for(int i=0;i<5;i++){ System.out.println(Thread.currentThread().getName()+"進攻對方["+i+"]次"); //讓出處理器時間,下次該誰進攻還不必定 Thread.yield(); } } System.out.println(Thread.currentThread().getName()+"結束了戰鬥!"); } } /** * 關鍵人物類 * @author gent * */ public class KeyPersonThread extends Thread{ public void run(){ System.out.println(Thread.currentThread().getName()+"開始了戰鬥"); for(int i=0;i<10;i++){ System.out.println(Thread.currentThread().getName()+"左突右殺,攻擊隋軍"); } System.out.println(Thread.currentThread().getName()+"結束了戰鬥"); } } /** * 隋唐演繹舞臺 * @author gent * */ public class Stage extends Thread { public void run(){ System.out.println("歡迎觀看隋唐演義"); try { Thread.sleep(5000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArmyRunnable armyTaskOfDynasty = new ArmyRunnable(); ArmyRunnable armyTaskOfRevolt = new ArmyRunnable(); //使用Runnable接口建立線程 Thread armyOfSuiDynasty = new Thread(armyTaskOfDynasty,"隋軍"); Thread armyOfRevolt = new Thread(armyTaskOfRevolt,"農民起義軍"); //啓動線程,讓軍隊開始做戰 armyOfSuiDynasty.start(); armyOfRevolt.start(); //舞臺線程休眠,你們專心觀看軍隊廝殺 try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("正當雙方激戰正酣,半路殺出個程咬金"); Thread mrCheng = new KeyPersonThread(); mrCheng.setName("程咬金"); System.out.println("程咬金的理想就是結束戰爭,使百姓安居樂業!"); //鳴金收兵 //中止線程的方法 armyTaskOfDynasty.keepRunning=false; armyTaskOfRevolt.keepRunning=false; //不該該使用stop方法中止線程,由於這是一種戛然而止的方式 try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } mrCheng.start(); try { mrCheng.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("戰爭結束,人民安居樂業,程先生實現了人生理想!"); System.out.println("演出結束"); // try { // armyOfRevolt.join(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } public static void main(String[] args) { new Stage().start(); } }