关于解析面试题第三题的“线程终止运行”这句话
来源:9-3 处理异常

丨木頭丶吅
2020-04-14
老师,您在解析面试题第三题的时候,说:
首先run方法是不能在方法签名抛出异常的,只能主动throw或者自己在方法中try catch处理。如果是RuntimeException,没有提前做捕获,会抛出一个异常,并且线程终止运行并打印异常堆栈。
但是在CanCatchInRun和ExceptionInChildThread这两个类中,抛出异常后,主线程并没有停止啊,如果您说的停止运行是指run方法停止运行,可run方法就执行了一个抛出异常,在抛出的行后写代码编译器都会提示运行不到这里。不太明白您这里指的哪个终止运行了。
public static void main(String[] args) throws InterruptedException {
// 2、加了try
// try {
// 1、不加try
new Thread(new CanCatchInRun(), "MyThread-1").start();
Thread.sleep(300);
new Thread(new CanCatchInRun(), "MyThread-2").start();
Thread.sleep(300);
new Thread(new CanCatchInRun(), "MyThread-3").start();
Thread.sleep(300);
new Thread(new CanCatchInRun(), "MyThread-4").start();
Thread.sleep(300);
// } catch (RuntimeException e) {
// System.out.println("Caught Exp ");
// e.printStackTrace();
// }
}
@Override
public void run() {
throw new RuntimeException();
}
public class ExceptionInChildThread implements Runnable {
public static void main(String[] args) {
new Thread(new ExceptionInChildThread()).start();
for (int i = 0; i < 199; i++) {
System.out.println(i);
}
}
@Override
public void run() {
throw new RuntimeException();
}
}
写回答
1回答
-
悟空
2020-04-14
对应的子线程会停止,也就是指run方法停止运行
10
相似问题