終止執行緒的方法(不看後悔,看了必懂)
在java語言中,可以使用stop()方法和suspend()方法來終止執行緒的執行.
當使用Thread.stop()來終止執行緒時,它會釋放已經鎖定的所有監視資源,具有不安全性
suspend()方法不會釋放鎖,容易發生死鎖(兩個或者兩個以上程序在執行過程中,因爭奪資源而造成程序間互相等待的現象,如果無外力干涉,它們將無法推進)問題
鑑於以上兩種方法的不安全性,java語言已經不建議使用以上兩種方法來終止執行緒了
思想:
讓執行緒自行進入Dead狀態,如果想要停止一個執行緒的執行,就提供某種方式讓執行緒自動結束run()方法的執行
方法①:
通過設定一個flag標誌來控制迴圈是否執行
public class MyThread implements Runnable{
pirvate volatile Boolean flag;
public void stop(){
flag=false;
}
public void run(){
while(flag){
.......
}
}
}
方法②
上面的方法存在問題,當執行緒處於非執行狀態時(當sleep()方法被呼叫或者當wait()方法被呼叫或者當被I/O阻塞時),上面的方法就不能用了.此時可以通過interrupt()方法來打破阻塞的情況,當interrupt()方法被呼叫時,會丟擲InterruptedException異常,可以通過run()方法捕獲這個異常來讓執行緒安全退出
public class MyThread{
public static void main(String [] args){
Thread thread=new Thread(new Runnable(){
public void run(){
System.out.println(“thread go to sleep”);
try{
//使用執行緒休眠模擬執行緒被阻塞
Thread.sleep(5000);
}catch(InterruptedException e){
System.out.println(“thread is interrupted”);
}
}
});
thread.start();
thread.interrupt();
}
}
輸出結果為:
thread go to sleep
thread is interrupted