線程中斷問題詳解

//線程的中斷操作(1)
class MyThread implements Runnable
{
	public void run(){
		System.out.println("1、進入run方法");
		try{
			Thread.sleep(10000);       //sleep方法會拋出一箇中斷異常
		}catch(InterruptedException e){
			System.out.println("2、線程被中斷");  //當sleep被打斷時,則執行此中斷處理
		}
		System.out.println("3、run方法執行完成");
	}
}
public class ThreadInterruptDemo01
{
	public static void main(String args[]){
		MyThread my = new MyThread();
		Thread t = new Thread(my);
		t.start();
		try{
			Thread.sleep(2000);   //主線程休息2秒
		}
		catch(Exception e){}
		t.interrupt();    //中斷線程
	}
	
	
}

//線程的中斷操作(2)線程沒有被中斷,interrupt只能中斷sleep,wait等方法
class MyThread implements Runnable
{
	public void run(){
		System.out.println("1、進入run方法");
		for(int i = 0;i<=10000;i++){
			System.out.println("線程在執行"+"--"+i);
		}
		System.out.println("線程正常執行完畢");
	}
}
public class ThreadInterruptDemo02
{
	public static void main(String args[]){
		MyThread my = new MyThread();
		Thread t = new Thread(my);
		t.start();
		
		t.interrupt();    //中斷線程
	}
}

通過兩段代碼的運行結果可以知道,代碼1的中斷實現了,而代碼2的中斷沒有實現,interrupt並沒有中斷線程的執行,而是中斷了sleep的執行。原因何在,這與Interrupt的中斷內容有關。interrupt只能中斷sleep,wait等方法,而通過查詢api可以看到,sleep和wait都有InterruptedException(中斷異常)需要處理。所以可以這樣看:interrupt只能中斷會拋出中斷異常的方法,這纔是interrupt的實際作用。

還有一點需要注意,當sleep方法被中斷後,sleep方法後的內容依然會被執行,相當於線程被喚醒進入了正常執行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章