我自己試驗了下,如果sleep時間過短,會導(dǎo)致join后還是被插隊。求解!
package?thread; /** ?*?軍演舞臺 ?*/ public?class?Stage?extends?Thread{ @Override public?void?run()?{ //創(chuàng)建紅藍方攻擊的實例 ArmyRunnable?redAttack0?=?new?ArmyRunnable(); ArmyRunnable?blueAttack0?=?new?ArmyRunnable(); //創(chuàng)建線程 Thread?redAttack?=?new?Thread(redAttack0,"紅方軍團"); Thread?blueAttack?=?new?Thread(blueAttack0,"藍方軍團"); //軍演戰(zhàn)斗的帷幕徐徐拉開 System.out.println("軍演戰(zhàn)斗的序幕徐徐拉開······"); try?{ Thread.sleep(5000); }?catch?(InterruptedException?e1)?{ //?TODO?Auto-generated?catch?block e1.printStackTrace(); } //啟動線程,開始作戰(zhàn) redAttack.start(); blueAttack.start(); //關(guān)閉舞臺線程,保證軍演專心進行一會兒。否則程咬金會提前登場! //同時sleep時間太短(比如休眠25ms)會導(dǎo)致軍團線程插入程咬金線程,為什么????????????????????? try?{ // this.sleep(50);//這種方法也可以,或者Thread.sleep(50) sleep(50);//簡寫. }?catch?(InterruptedException?e)?{ e.printStackTrace(); } //半路殺出個Hero! System.out.println("半路殺出個程咬金!"); //創(chuàng)建英雄程咬金線程,并開啟 Hero?hero?=?new?Hero(); Thread?chengyj?=?new?Thread(hero,"程咬金"); chengyj.start(); try?{ chengyj.join(); }?catch?(InterruptedException?e)?{ //?TODO?Auto-generated?catch?block e.printStackTrace(); } //結(jié)束兩個軍團線程,需要最后一遍循環(huán)結(jié)束 redAttack0.keepRunning=false; blueAttack0.keepRunning=false; //給兩個軍團線程結(jié)束一點兒時間 try?{ Thread.sleep(2000); }?catch?(InterruptedException?e)?{ //?TODO?Auto-generated?catch?block e.printStackTrace(); } System.out.println("軍演結(jié)束!"); } public?static?void?main(String[]?args)?{ //啟動舞臺,開始觀戰(zhàn) new?Stage().start(); } }
第一次sleep時,50ms可以保證不被插隊,但是25ms就會出現(xiàn)下圖所示:
2017-07-10
你代碼順序錯了,應(yīng)該先停止雙方線程,然后再讓關(guān)鍵線程運行。