SCJP: Program not terminating after uncaught excep

2019-07-24 18:18发布

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?

6条回答
你好瞎i
2楼-- · 2019-07-24 18:20

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.

查看更多
地球回转人心会变
3楼-- · 2019-07-24 18:40

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

查看更多
叼着烟拽天下
4楼-- · 2019-07-24 18:43

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

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

查看更多
Root(大扎)
5楼-- · 2019-07-24 18:43

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)
查看更多
不美不萌又怎样
6楼-- · 2019-07-24 18:46

Not program but thread terminates. Main program continues execution.

查看更多
狗以群分
7楼-- · 2019-07-24 18:47

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.

查看更多
登录 后发表回答