關於sleep()和interrupt()及主線程和線程


看代碼

public class TestSleep {
    public static void main(String args[]) throws InterruptedException{
        Thread t1 = new CountThread();
        t1.start();
        Thread.sleep(6000);
        System.out.println("即將中斷阻塞");
        t1.interrupt();
    }
}
public class CountThread extends Thread{
    private int i = 1;
    
    public CountThread(){
        super("計數線程");
    }
    public void run(){
        while(i<100){
            System.out.println(this.getName()+"計數"+i);
            i++;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                System.out.println("系統捕獲了中斷異常");
            }
        }
    }
}

看結果

 

計數線程計數1

計數線程計數2
即將中斷阻塞
系統捕獲了中斷異常

計數線程計數3

計數線程計數4

計數線程計數5

現在看結果,帶着問題來看。

為什么中斷會發生在第二次循環開始?

  這里就要涉及主線程的問題。當我們創建一個線程是在主線程的基礎上,創建一條線程那也是多線程。這里的中斷時對於t1這個對象來說,它並不具有中斷主線程的能力。也就是,當主線程阻塞的時候,t1.interrupt();沒法執行,但是計數線程還在走,第一個循環的sleep()就沒能被中斷。那么當主線程阻塞結束后,t1.interrupt();開始執行,這時候第二次的sleep(5000)被中斷。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM