java經常使用的結束一個運行中的線程的方法有3中:使用退出標誌,使用interrupt方法,使用stop方法。java
即在線程內部定義一個bool變量來判斷是否結束當前的線程:安全
public class ThreadSafe extends Thread { public volatile boolean exit = false; public void run() { while (!exit){ //do work } } public static void main(String[] args) throws Exception { ThreadFlag thread = new ThreadFlag(); thread.start(); sleep(5000); // 主線程延遲5秒 thread.exit = true; // 終止線程thread thread.join(); System.out.println("線程退出!"); } }
這種狀況通常是將線程的任務放在run方法中的一個while循環中,而由這個bool變量來對while循環進行控制。socket
這種方法須要判斷當前的線程所處於的狀態:
(1)當前線程處於阻塞狀態時
線程處於阻塞狀態通常是在使用了 sleep,同步鎖的 wait,socket 中的 receiver,accept 等方法時,會使線程處於阻塞狀態。線程
public class ThreadInterrupt extends Thread { public void run() { try { sleep(50000); // 延遲50秒 } catch (InterruptedException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) throws Exception { Thread thread = new ThreadInterrupt(); thread.start(); System.out.println("在50秒以內按任意鍵中斷線程!"); System.in.read(); thread.interrupt(); thread.join(); System.out.println("線程已經退出!"); } }
注意這種狀況寫,使用 interrupt 方法結束線程的時候,必定要先捕獲 InterruptedException 異常以後經過 break 來跳出循環,才能正常結束 run 方法。code
(2)線程未處於阻塞狀態時get
使用 isInterrupted() 判斷線程的中斷標誌來退出循環。當使用 interrupt() 方法時,中斷標誌就會置 true,和使用自定義的標誌來控制循環是同樣的道理。同步
public class ThreadSafe extends Thread { public void run() { while (!isInterrupted()) { //非阻塞過程當中經過判斷中斷標誌來退出 try { Thread.sleep(5*1000); //阻塞過程捕獲中斷異常來退出 } catch (InterruptedException e) { e.printStackTrace(); break; //捕獲到異常以後,執行 break 跳出循環 } } } }
public class Main { public static void main(String[] args) throws InterruptedException { MyThread myThread = new MyThread(); myThread.start(); Thread.sleep(3000); // 間隔3秒後 myThread.stop(); // 結束線程 System.out.println("結束了"); } }
建議使用標誌位和interrupt方法來結束線程,stop方法已經不建議再被使用了。
由於採用 stop 是不安全的,主要影響點以下:it