I’ve been doing some practice for my O/SCJP exam. Consider the following code:
public class Cruiser implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new Cruiser());
a.start();
System.out.print("Begin");
a.join();
System.out.print("End");
}
public void run() {
System.out.print("Run");
}
}
Source: http://scjptest.com/mock-test.xhtml
The site states the output (the answer to their mock question) will be BeginRunEnd and, when running the class normally, that’s exactly what is output.
However, when debugging the output is RunBeginEnd.
Is it fair to say that under normal execution, the output will always be BeginRunEnd or would this vary depending on other factors (like how heavy the new thread class is / how long after starting the thread it takes to join it)?
Would you say it’s a fair / accurate exam question?
I think BeginRunEnd is more likely than RunBeginEnd (I’d expect the act of actually starting up the new thread to take a while before it got to the
runmethod, and for the first thread to get to the print before it runs out of its timeslice in most cases), but it would be flat out incorrect to assume that when programming.You should regard the two threads as completely independent as soon as
startis called, until they’re explicitly tied together again with thejoincall. Logically, the new thread could run all the way to completion before the main thread prints “Begin”.Looks like a bad question to me.