Java - Thread join() and order of execution SCJP question?
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 run
method, 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 start
is called, until they're explicitly tied together again with the join
call. Logically, the new thread could run all the way to completion before the main thread prints "Begin".
Looks like a bad question to me.
This is a rubbish question. The outcome is undefined without synchronisation.
Is this really bofa fida SCJP question, or just one made up by some site trying to sell SCJP training? If its the latter then I'd avoid that site like the plague.
This is likely to be platform dependant, but to show the order can change.
public class Cruiser implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new Cruiser());
a.setPriority(Thread.MAX_PRIORITY);
a.start();
// Thread.sleep(1);
System.out.print("Begin");
a.join();
System.out.print("End");
}
public void run() {
System.out.print("Run");
}
}
prints the first time I ran it.
RunBeginEnd
however after that its mostly the BeginRunEnd
If the thread stops, even for 1 ms it will produce the RunBeginEnd nearly every time.
精彩评论