In the below code what could be the predicted output?
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.");
}
}
The possible outcome given as the answers are:
End of method.
run.
java.lang.RuntimeException: Problem
OR
run.
java.lang.RuntimeException: Problem
End of method.
According to me only answer 2nd is possible, please help me to understand.
The execution will result in two threads, the main thread (the one running the main-method), and the thread created in the main method. Since you can’t guarantee anything when it comes to the order that the threads will run, there are multiple orders that the code could run.
So lets call the main thread Thread1, and the created thread Thread2. The possibilties then are, after Thread2 has been started:
and, there is actually a third possibility (i think):