【发布时间】:2015-11-27 06:48:25
【问题描述】:
我想知道在第一个线程的 run 方法中中断另一个线程是否非法。如果是,当我在第一个线程的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() 行上收到“通过实例访问静态方法”警告。这是在警告您 Keppil 在他们的回答中所说的内容
-
我有这个。一路走来非常感谢! --)
标签: java multithreading interrupt