SCJP:程序在未捕获的异常后未终止
public class Threads2 implements Runnable {
public void run() {
System.out.println("run.");
throw new RuntimeException("Problem");
}
public static void main(String[] args) {
Thread t = new Thread(new Threads2());
t.start();
System.out.println("End of method.");
}
}
我预测输出为
run.
//exception
但它显示输出为,
run
exception
end of method
(或者)
run
end of method
exception
我想知道,一旦发生异常,程序就会终止,对吧?
public class Threads2 implements Runnable {
public void run() {
System.out.println("run.");
throw new RuntimeException("Problem");
}
public static void main(String[] args) {
Thread t = new Thread(new Threads2());
t.start();
System.out.println("End of method.");
}
}
I predicted the output as
run.
//exception
But it is showing output as,
run
exception
end of method
(or)
run
end of method
exception
I wonder, once the exception has occurred the program will terminate, right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您观察到该问题,则您正在明确创建一个线程t。当你运行代码时,main方法将运行,这里jvm也会为主类创建一个线程。这意味着代码有两个线程。一个是t,另一个是主类线程。这里main()线程是父线程,t线程是子线程。当子线程中发生异常时,它会终止并且父线程将运行。所以输出可能是任何顺序。
问候,
詹姆斯
If you observe the question you are creating a thread t explicitly. when you run code main method will run, here jvm will create a thread for main class also. that means there are two threads for the code. one is t and other is main class thread. Here main() thread is parent thread and the t thread is child thread. As the exception occurs in child thread it gets terminated and the parent thread will run. So the output might be any of the order.
Regards,
James
不是程序而是线程终止。主程序继续执行。
Not program but thread terminates. Main program continues execution.
不,您的程序不会终止,但线程会终止。
当线程抛出未捕获的异常时,它就会终止。您的
main
线程继续运行。No, your program does not terminate, but the thread does.
When a thread throws an uncaught exception it terminates. Your
main
thread continues running.首先,你得到的输出不是最终的。如果是多线程,则取决于机器。在不同的机器上可能会出现一些不同的输出。
出现异常时,正在运行的线程执行终止。其他线程继续执行。
First thing, the output you got is not the final. It depends on machine in case of multi-threading. On different machine some different output might come.
On exception, the running thread execution terminates. Other thread continue their execution.
你自己看看吧。在我的机器上我得到:
See for yourself. On my machine I get:
这就是多线程的美妙之处!!
您编写的每个 Java 程序都有一个运行它的线程,通常是主线程。在您的情况下,您创建了自己的线程,其父线程是主线程。当你的子线程抛出异常时,它会结束,但主线程仍然没有完成。所以它打印的是最后一个语句,然后结束。
对于线程,无法预测行为[因为它取决于 JVM 从可运行池中选择项目的策略],因此您看到的顺序在不同的运行中可能会有所不同。
This is the beauty of multithreading!!
Every java program you write has a thread running it which is normally a main thread. In your case you have created your own thread whose parent thread is main thread. When your child thread throws an exception, it ends but main thread is still not complete. So it prints is last statement and then ends.
In case of threads the behavior can not be predicted [as it depends on JVM's policy to pick items from runnable pool] so the order you see might be different in different runs.