【发布时间】:2021-04-13 10:31:09
【问题描述】:
我试图了解异常如何在多线程中传播。
问题
在下面的例子中。
为什么RuntimeException 异常没有被捕获
`System.out.println("Exception handled " + e);
给定代码
package p05_Interrupt;
public class D05_Interrupt1 extends Thread {
public void run() {
try {
Thread.sleep(1000);
System.out.println("task");
} catch (InterruptedException e) {
throw new RuntimeException("Thread interrupted..." + e);
}
}
public static void main(String args[]) {
D05_Interrupt1 t1 = new D05_Interrupt1();
t1.start();
try {
t1.interrupt();
} catch (Exception e) {
System.out.println("Exception handled " + e); // Why not print this line
}
}
}
1st example in JavaTpoint "Example of interrupting a thread that stops working"
输出
Exception in thread "Thread-0" java.lang.RuntimeException: Thread interrupted...java.lang.InterruptedException: sleep interrupted
at p05_Interrupt.D05_Interrupt1.run(D05_Interrupt1.java:9)
是不是因为这是多线程,所以在线程t1打印异常,隐藏main()线程的输出?
我还尝试在 public void run() throws RuntimeException { 添加 throws 并没有改变任何东西。
【问题讨论】:
标签: java multithreading exception parallel-processing