Friday, September 15, 2023

Difference between start and run method in Thread? Example

Why to do one call start method of the thread if start() calls run() in turn" or "What is the difference by calling start() over run() method in java thread" are two widely popular beginner level multi-threading interview question. When a Java programmer start learning Thread, the first thing he learns is to implement thread either overriding run() method of Thread class or implementing Runnable interface and then calling start() method on the thread, but with some experience, he finds that start() method calls run() method internally either by looking API documentation or just poking around, but many of us just don’t care at that time until it been asked in Java Interview.


In this Java tutorial, we will see What is the difference between calling start() method and run() method for starting Thread in Java.

This article is in continuation of my earlier post on Java multi-threading e.g. Difference between Runnable and Thread in Java and How to solve Producer Consumer problem in Java using BlockingQueue. If you haven’t read them already you may find them interesting and useful.


Difference between start and run in Java Thread

start vs run method in Java with ExampleSo what is the difference between the start and run method? Main difference is that when program calls start() method a new Thread is created and code inside run() method is executed in new Thread while if you call run() method directly no new Thread is created and code inside run() will execute on the current Thread

Most of the time calling run() is bug or programming mistake because the caller has the intention of calling start() to create a new thread and this error can be detected by many static code coverage tools like find bugs. 

If you want to perform a time-consuming task then always call the start() method otherwise your main thread will be stuck while performing a time-consuming task if you call run() method directly. 

Another difference between start vs run in Java thread is that you can not call start() method twice on the thread object. once started, the second call of start() will throw IllegalStateException in Java while you can call run() method twice. You can further see Java Multithreading courses to learn more bout thread and how to use thread effectively in Java. 




Code Example of start vs run method

Here is a simple code example that prints the name of Thread which executes run() method of the Runnable task. It's clear that if you call start() method a new Thread executes Runnable task while if you directly call run() method task, current thread which is main in this case will execute the task.

public class StartVsRunCall{

   
public static void main(String args[]) {
       
       
//creating two threads for start and run method call
        Thread startThread =
new Thread(new Task("start"));
        Thread runThread =
new Thread(new Task("run"));
       
        startThread.
start(); //calling start method of Thread - will execute in new Thread
        runThread.
run();  //calling run method of Thread - will execute in current Thread

   
}

   
/*
     * Simple Runnable implementation
     */

   
private static class Task implements Runnable{
       
private String caller;
       
       
public Task(String caller){
           
this.caller = caller;
       
}
       
        @Override
       
public void run() {
            System.
out.println("Caller: "+ caller + " and code on this Thread is executed by : " + Thread.currentThread().getName());
           
       
}        
   
}
}

Output:
Caller: start and code on this Thread is executed by : Thread-0
Caller: run and code on this Thread is executed by : main


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.


Other Java tutorials on Thread you may like

And lastly one question for you? On which class wait and notify methods are defined? Thread class or Object class? Bonus point if you can explain why they are defined into that particular class?

4 comments:

  1. In most cases a direct call to a Thread object's run() method is a bug. The programmer wnated to start a new thread for parallel execution, but accidentally called run() instead of start(), so the run() method will execute in the caller's thread of control. By the way its easy to detect bug, if you are using static code analyzer like Findbugs or HP Fortify. Almost all code coverage and static analysis tools has rules to detect such bugs during development. In many firms fortify scanning of new code is mandatory.

    ReplyDelete
  2. once started, second call of start() will throw IllegalStateException in Java while you can call run() method twice.
    Here it JVM will throw IllegalThredStateException. i.e. The thread is not in the valid state for the operation which user is trying to perform.

    ReplyDelete
  3. @Tejpal, very valid point. Calling start() method twice on a thread object definitely throws IllegalThreadStateException.

    ReplyDelete
  4. why we override run method in java?

    ReplyDelete