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();
}
但我沒有消息在控制檯中。
您應該在線程thread1.sleep()上獲取「通過實例訪問靜態方法」警告。這是警告你關於凱皮爾在回答中說什麼 –
我有這個。非常感謝你! - ) – zhongwei