For the below program different outputs are coming when running and debugging on eclipse.
public class MyClass implements Runnable {
public static void main (String[] args) throws Exception {
Thread t = new Thread(new MyClass());
t.start();
System.out.print("Started");
t.join();
System.out.print("Complete");
}
public void run() {
for (int i = 0; i < 4; i++) {
System.out.print(i);
}
}
}
When running this as java application the OUTPUT is
Started0123Complete
When checking in Debug Mode OUTPUT is
0123StartedComplete
Can someone help on this? is it because of two threads? main thread
and the thread which starts with t.start()
.If yes then why main thread execution is taking more priority to complete first?
Thanks
It's coincidence. You can't control the thread scheduler.
However, in a debug environment, the debugger plugs into your code to inspect values and execution. This inspection increases the amount of work done per thread time slice.
For example, in a regular run, the main thread may only need 1 time slice to create the new thread object, start it, and print the Started
message. Then a context switch would occur and the second thread would get a chance to work. In a debug run, the main thread would only have enough time to create the new thread object and start the corresponding thread. Then the context switch would occur and the other thread would do its thing.