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();
}
}
start method of thread class is implemented as when it is called a new Thread is created and code inside run() method is executed in that new Thread. While if run method is executed directly than no new Thread is created and code inside run() will execute on current Thread and no multi-threading will take place.
In Summary only difference between the start() and run() method in Thread is that start creates a new thread while the run doesn't create any thread and simply executes in the current thread like a normal method call.
The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed.
Explanation: run() method is used to define the code that constitutes the new thread, it contains the code to be executed. start() method is used to begin execution of the thread that is execution of run(). run() itself is never used for starting execution of the thread.
run() methods: New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed.
start() and run() methods are used for running a thread. The run() method is just an ordinary method, it is overridden by the user and it will be called on the current thread. The start() method runs the run() method indirectly and creates a new thread.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With