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?
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.
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
No, your program does not terminate, but the thread does.
When a thread throws an uncaught exception it terminates. Your
main
thread continues running.See for yourself. On my machine I get:
Not program but thread terminates. Main program continues execution.
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.