Please explain the output of the below code:
If I call th1.run(), the output is:
EXTENDS RUN>>
RUNNABLE RUN>>
If I call th1.start(), the output is:
RUNNABLE RUN>>
EXTENDS RUN>>
Why this inconsistency? Please explain.
class ThreadExample extends Thread{
public void run() {
System.out.println("EXTENDS RUN>>");
}
}
class ThreadExampleRunnable implements Runnable {
public void run() {
System.out.println("RUNNABLE RUN>>");
}
}
class ThreadExampleMain{
public static void main(String[] args) {
ThreadExample th1 = new ThreadExample();
//th1.start();
th1.run();
ThreadExampleRunnable th2 = new ThreadExampleRunnable();
th2.run();
}
}
The
Thread.start()method starts a new thread, the entry point for this thread is therun()method. If you call run() directly it will execute in the same thread. Given that callingThread.start()will start a new thread of execution, therun()method may be called after (as in you example) the rest of the main method executes.Change your main method to call
th1.start()and run repeatedly, you will see that sometimes it outputs:and sometimes it outputs:
depending on how java chooses to schedule your 2 threads.
Check out the java tutorial on this.