使用start()方法能夠啓動線程。java
start()方法的含義是告知線程規劃器線程已初始化完畢,能夠分給這個線程時間片了(執行run()方法)。安全
import java.util.concurrent.TimeUnit; public class Shutdown { public static void main(String[] args) throws Exception { Runner one = new Runner(); Thread countThread = new Thread(one, "CountThread"); countThread.start(); // 睡眠1秒,main線程對CountThread進行中斷,使CountThread可以感知中斷而結束 TimeUnit.SECONDS.sleep(1); countThread.interrupt(); Runner two = new Runner(); countThread = new Thread(two, "CountThread"); countThread.start(); // 睡眠1秒,main線程對Runner two進行取消,使CountThread可以感知on爲false而結束 TimeUnit.SECONDS.sleep(1); two.cancel(); } private static class Runner implements Runnable { private long i; private volatile boolean on = true; @Override public void run() { while (on && !Thread.currentThread().isInterrupted()) { i++; } System.out.println("Count i = " + i); } public void cancel() { on = false; } } }
Count i = 364902562多線程
Count i = 239832801ide
代碼中target爲one時是使用interrupt(),運行中的線程(main主線程)調用線程countThread的interrupt()方法,向countThread線程打了個「招呼」,對countThread線程作了中斷操做。咱們看JDK源碼中interrupt()方法的源碼:spa
看註釋:線程
// Just to set the interrupt flagcode
說的很是明白,對標識位進行了設置。就是將 interrupt flag 設置爲true。將線程的中斷標識位 interrupt flag 屬性設置爲了true。blog
因此while條件中 Thread.currentThread().isInterrupted() 返回爲true。而後代碼跳出了while循環。資源
代碼中target爲two時是顯式地將中止標識變量on(爲volatile變量)變爲false,而後跳出while循環。get
Thread的stop()方法也能夠終止線程,可是很直接暴力,並且可能會引發死鎖。
因此stop()方法被被遺棄了。
使用【中斷操做】和【volatile修飾的中止標識變量】的方式中止線程,使線程在終止時有機會清理資源。
1.run()方法中通常都有while條件。
2.將中止標識變量(最好定義爲volatile變量,多線程場景下可以立馬讀取該變量)寫入while條件。
3.顯式的調用改變中止標識變量的方法,就能夠安全而優雅的中止線程了。