Please explain the output from Thread run() and start() methods
The Thread.start()
method starts a new thread, the entry point for this thread is the run()
method. If you call run() directly it will execute in the same thread. Given that calling Thread.start()
will start a new thread of execution, the run()
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:
EXTENDS RUN>>
RUNNABLE RUN >>
and sometimes it outputs:
RUNNABLE RUN >>
EXTENDS RUN>>
depending on how java chooses to schedule your 2 threads.
Check out the java tutorial on this.
When you call th1.run()
you are running the run
method in the current thread, so thus must happen before call to th2.run()
.
When you call th1.start()
you the run
method is being called on a new thread. In this case it is happening after the call to th2.run()
. (In fact, it is theoretically possible that it could happen before the th2.run()
... but current and previous Sun implementations of thread.start()
do not cause the current thread to immediately "yield" to the new thread.)
This illustrates a common mistake with using Java threads. If you want to run stuff on a new thread, you must call thread.start()
. Directly calling thread.run()
is almost always a mistake.