In the below code the answer is always Started 0 1 2 3 Complete. Im just wondering how it is possible.
If someone could help with the consistency of the output, it would be nice
public class TestOne extends Thread {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Thread t = new Thread(new TestOne());
t.start();
System.out.println("started");
t.join();
System.out.println("Complete");
}
public void run(){
for(int i=0;i<4;i++){
System.out.println(i);
}
}
Most likely you’re getting the same results because, most of the time, the main thread starts a new thread then, before that new thread has a chance to print anything, the main thread prints its
startedmessage. Thejoinin the main thread then forces it to wait until the other thread has finished, then it printsComplete.You have a race condition here. The instant you start the second thread, it’s indeterministic as to which order the lines will be output (other than the
completeline which is made deterministic by virtue of thewaitcall, as previously mentioned).But a race condition doesn’t guarantee that you’ll get different results on multiple runs, only that it is possible. You still shouldn’t rely on that behaviour, of course.
For example, the following code:
will output:
Although, even then, the order is not guaranteed as it may take more than a second for the thread to “warm up” –
sleepis rarely a good solution to race conditions. I’ve just used it here for illustrative purposes.