//軍隊線程 //模擬做戰雙方的行爲 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()+"結束了戰鬥!"); } }
package com.wistron.swpc.ecs.util; 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()+"結束了戰鬥!"); } }
package com.wistron.swpc.ecs.util; /** * 隋唐演義大戲舞臺 */ public class Stage extends Thread { public void run(){ System.out.println("歡迎觀看隋唐演義"); //讓觀衆們安靜片刻,等待大戲上演 try { Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } System.out.println("大幕徐徐拉開"); try { Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } System.out.println("話說隋朝末年,隋軍與農民起義軍殺得昏天黑地..."); ArmyRunnable armyTaskOfSuiDynasty = new ArmyRunnable(); ArmyRunnable armyTaskOfRevolt = new ArmyRunnable(); //使用Runnable接口建立線程 Thread armyOfSuiDynasty = new Thread(armyTaskOfSuiDynasty,"隋軍"); 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("程咬金的理想就是結束戰爭,使百姓安居樂業!"); //中止軍隊做戰 //中止線程的方法 armyTaskOfSuiDynasty.keepRunning = false; armyTaskOfRevolt.keepRunning = false; try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } /* * 歷史大戲留給關鍵人物 */ mrCheng.start(); //萬衆矚目,全部線程等待程先生完成歷史使命 try { mrCheng.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("戰爭結束,人民安居樂業,程先生實現了積極的人生夢想,爲人民做出了貢獻!"); System.out.println("謝謝觀看隋唐演義,再見!"); } public static void main(String[] args) { new Stage().start(); } }
以上經過html
ArmyRunnable 類中的keepRunning來判斷是否終止線程,keepRunning使用volatile標識符,關於volatile標識符請參考http://www.importnew.com/24082.html