Run or Start

Threading is a way too broad and important concept in Java technology and not only java technology it’s a crucial term in computer science as well. Threading, specifically in java is used in almost every professional programming. Most of programmers might have faced following question in interview,

What is the difference between run method and start method of Thread ?

Here run and start both may look similar to us but has a nano difference between them. Consider following example first,

class IMRunnable implements Runnable {
   
   @Override
   public void run() {
      String currentThreadName = Thread.currentThread().getName();
      System.out.println("I am running for: " +currentThreadName);
   }
}

public class ThreadDemo {
	
	public static void main(String[] args) {
		 IMRunnable imRunnable = new IMRunnable();
		 
		 Thread thread = new Thread(imRunnable);
         thread.run();
		 thread.start();
	}
}

and when you execute above program you will notice following output,

I am running for: main
I am running for: Thread-0

Now as you have two different outputs for the same run method. It’s crystal clear that both are behaving differently in this program.

threadStartVsRun

Here, when you call the run method of a thread it’s nothing more than a simple method call to the runnable instance of the Thread and it has nothing to do with threading and just exactly behave like any other method call, reason is when you call run method of thread it is not creating another Thread instance in the JVM but just executes the run method in current thread. So that you are actually executing the run method in your current Thread.

While on the other side start method of the Thread actually starts the new thread and than run, in other way executes the run method of runnable instance in a brand new ‘Thread – 0’.

start executes run in new Thread while call to run is just a common method call

Ultimately the call to the run method directly useless as there is no intentional use of it in development because why do you implement runnable and create Thread instance to call run method which will not going to have execution in new Thread.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s