2015-11-27 83 views
1

我想知道是否在第一個線程的運行方法中中斷另一個線程是非法的。如果是,當我在第一個線程的run方法中調用另一個線程的中斷方法時,是否會拋出「InterruptedException」?這樣的:「!哎呀,我打斷」一個線程可以中斷另一個線程嗎?

public static void main(String[] args) { 

    Thread thread1 = new Thread(() -> { 
     while (true) { 

     } 
    }, "thread1"); 
    try { 
     thread1.sleep(10000); 
    } catch (InterruptedException e) { 
     System.out.println("Oops! I'm interrupted!"); 
    } 
    Thread thread2 = new Thread(() -> { 
     System.out.println("I will interrupt thread1!"); 
     thread1.interrupt(); 
     System.out.println("Thread1 interruption done!"); 
    }, "thread2"); 
    thread1.start(); 
    thread2.start(); 
} 

但我沒有消息在控制檯中。

+1

您應該在線程thread1.sleep()上獲取「通過實例訪問靜態方法」警告。這是警告你關於凱皮爾在回答中說什麼 –

+0

我有這個。非常感謝你! - ) – zhongwei

回答

5

您的程序無法正常工作的原因是您正在使用thread1引用來訪問靜態sleep()方法,但睡眠仍在主線程中執行。
將它變成thread1的身體,你的程序正常工作:

public static void main(String[] args) { 
    Thread thread1 = new Thread(() -> { 
     try { 
      Thread.sleep(10000); 
     } catch (InterruptedException e) { 
      System.out.println("Oops! I'm interrupted!"); 
     } 
    }, "thread1"); 

    Thread thread2 = new Thread(() -> { 
     System.out.println("I will interrupt thread1!"); 
     thread1.interrupt(); 
     System.out.println("Thread1 interruption done!"); 
    }, "thread2"); 
    thread1.start(); 
    thread2.start(); 
} 

此打印:

I will interrupt thread1! 
Thread1 interruption done! 
Oops! I'm interrupted! 

注意,最後兩個打印輸出的順序取決於線程調度,並可變化。

+0

看中!我非常感謝你! – zhongwei

相關問題