SCJP: Program not terminating after uncaught exception

白昼怎懂夜的黑 提交于 2019-12-11 12:19:43

问题


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?


回答1:


No, your program does not terminate, but the thread does.

When a thread throws an uncaught exception it terminates. Your main thread continues running.




回答2:


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.




回答3:


See for yourself. On my machine I get:

bartek@dragon:~/workspace/sandbox$ java Threads2 
End of method.
run.
Exception in thread "Thread-0" java.lang.RuntimeException: Problem
    at Threads2.run(Threads2.java:5)
    at java.lang.Thread.run(Thread.java:636)



回答4:


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.




回答5:


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




回答6:


Not program but thread terminates. Main program continues execution.



来源:https://stackoverflow.com/questions/5622278/scjp-program-not-terminating-after-uncaught-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!