出自:https://www.cnblogs.com/qufanblog/p/3951375.html
終止線程的三種方法
有三種方法可以使終止線程某宪。
1.? 使用退出標志,使線程正常退出锐朴,也就是當run方法完成后線程終止兴喂。
2.? 使用stop方法強行終止線程(這個方法不推薦使用,因為stop和suspend焚志、resume一樣衣迷,也可能發(fā)生不可預料的結果)。
3.? 使用interrupt方法中斷線程酱酬。
1. 使用退出標志終止線程
當run方法執(zhí)行完后壶谒,線程就會退出。但有時run方法是永遠不會結束的膳沽。如在服務端程序中使用線程進行監(jiān)聽客戶端請求汗菜,或是其他的需要循環(huán)處理的任務。 在這種情況下挑社,一般是將這些任務放在一個循環(huán)中陨界,如while循環(huán)。如果想讓循環(huán)永遠運行下去痛阻,可以使用while(true){……}來處理菌瘪。但要想使 while循環(huán)在某一特定條件下退出,最直接的方法就是設一個boolean類型的標志录平,并通過設置這個標志為true或false來控制while循環(huán) 是否退出麻车。下面給出了一個利用退出標志終止線程的例子缀皱。
package chapter2;
public class ThreadFlag extends Thread
{
public volatile boolean exit = false;
public void run()
{
while (!exit);
}
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("線程退出!");
}
}
在上面代碼中定義了一個退出標志exit斗这,當exit為true時,while循環(huán)退出啤斗,exit的默認值為false.在定義exit時表箭,使用了一個 Java關鍵字volatile,這個關鍵字的目的是使exit同步钮莲,也就是說在同一時刻只能由一個線程來修改exit的值免钻,
2. 使用stop方法終止線程
使用stop方法可以強行終止正在運行或掛起的線程彼水。我們可以使用如下的代碼來終止線程:
thread.stop();
雖然使用上面的代碼可以終止線程,但使用stop方法是很危險的极舔,就象突然關閉計算機電源凤覆,而不是按正常程序關機一樣,可能會產(chǎn)生不可預料的結果拆魏,因此盯桦,并不推薦使用stop方法來終止線程。
3. 使用interrupt方法終止線程
使用interrupt方法來終端線程可分為兩種情況:
(1)線程處于阻塞狀態(tài)渤刃,如使用了sleep方法拥峦。
(2)使用while(!isInterrupted()){……}來判斷線程是否被中斷卖子。
在第一種情況下使用interrupt方法略号,sleep方法將拋出一個InterruptedException例外,而在第二種情況下線程將直接退出洋闽。下面的代碼演示了在第一種情況下使用interrupt方法玄柠。
package chapter2;
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秒之內(nèi)按任意鍵中斷線程!");
System.in.read();
thread.interrupt();
thread.join();
System.out.println("線程已經(jīng)退出!");
}
}
上面代碼的運行結果如下:
在50秒之內(nèi)按任意鍵中斷線程!
sleep interrupted
線程已經(jīng)退出!
在調(diào)用interrupt方法后, sleep方法拋出異常诫舅,然后輸出錯誤信息:sleep interrupted.
注意:在Thread類中有兩個方法可以判斷線程是否通過interrupt方法被終止随闪。一個是靜態(tài)的方法interrupted(),一個是非靜態(tài)的方 法isInterrupted()骚勘,這兩個方法的區(qū)別是interrupted用來判斷當前線是否被中斷铐伴,而isInterrupted可以用來判斷其他 線程是否被中斷。因此俏讹,while (当宴!isInterrupted())也可以換成while (!Thread.interrupted())泽疆。
如何停止java的線程一直是一個困惱我們開發(fā)多線程程序的一個問題户矢。這個問題最終在Java5的java.util.concurrent中得到了回答:使用interrupt(),讓線程在run方法中停止殉疼。
在Java的多線程編程中梯浪,java.lang.Thread類型包含了一些列的方法start(),stop(),stop(Throwable)andsuspend(),destroy()andresume()。通過這些方法瓢娜,我們可以對線程進行方便的操作挂洛,但是這些方法中,只有start()方法得到了保留眠砾。
在Sun公司的一篇文章《Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?》中詳細講解了舍棄這些方法的原因虏劲。那么,我們究竟應該如何停止線程呢?
在《Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?》中柒巫,建議使用如下的方法來停止線程: