Difference between starting thread with run() and start() methods in java


This is quite interesting question, it might confuse you a bit and at time may make you think is there really any difference between run() and start() method.
When you call start() method, main thread internally calls run() method to start newly created Thread. So run() method is ultimately called by newly created thread.
When you call run() method main thread rather than starting run() method with newly thread it start run() method by itself.


Let’s use start() method to start a thread>

class MyRunnable implements Runnable{
   public void run(){   //overrides Runnable's run() method
          System.out.println("in run() method");
          System.out.println("currentThreadName= "+ Thread.currentThread().getName());
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
   public static void main(String args[]){
          System.out.println("currentThreadName= "+ Thread.currentThread().getName());
          MyRunnable runnable=new MyRunnable();
          Thread thread=new Thread(runnable);
          thread.start();
   }
}
/*OUTPUT
currentThreadName= main
in run() method
currentThreadName= Thread-0
*/
If we note output, when we called start() from main thread, run() method was called by new Thread (i.e. Thread-0).

Let’s use run() method to start a thread>

class MyRunnable implements Runnable{
   public void run(){   //overrides Runnable's run() method
          System.out.println("in run() method");
          System.out.println("currentThreadName= "+ Thread.currentThread().getName());
   }
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
   public static void main(String args[]){
          System.out.println("currentThreadName= "+ Thread.currentThread().getName());
          MyRunnable runnable=new MyRunnable();
          Thread thread=new Thread(runnable);
          thread.run();
   }
}
/*OUTPUT
currentThreadName= main
in run() method
currentThreadName= main
*/
If we note output, when we called run() from main thread, run() method was called by main Thread, not by newly created thread (i.e. Thread-0).




RELATED LINKS>


run() and Start() methods >

What will happen if we don’t override run method of thread?

What will happen if we override start method of thread?

Difference between starting thread with run() and start() methods in java

Can we start Thread again?

Volatile keyword vs synchronized>

Volatile keyword in java- difference between synchronized and volatile, 10 key points about volatile keyword, why volatile variables are not cached in memory

Differences between synchronized and volatile keyword in detail


Race Condition >

Race condition in multithreading and it's solution





No comments:

Post a Comment