Please explain the output from Thread run() and start() methods

java, multithreading

Solution

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.

Problem

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(); } } ```

Original source