Monday, June 13, 2022

What if run() Method Called Directly Instead of start() Method - Java MultiThreading

When we call start() method on the thread it causes the thread state to change to "Runnable". It’s the Java Virtual Machine that calls the run method of that thread to actually start the thread execution, run() method is not called directly. In this post you'll see what happens if run() method is called directly in Java multi-threading.

What if run method is called directly

If run() method is called directly instead of start() method in Java code, run() method will be treated as a normal overridden method of the thread class (or runnable interface). This run method will be executed with in the context of the current thread not in a new thread.

It’s the start() method that spawns a new thread and schedules the thread with the JVM. The JVM will let the newly spawned thread execute run() method when the resources and CPU are ready. So not calling the start method and directly calling the run() method will mean a new thread object is not created and run() method will run as a normal overridden method.

Calling run method directly example

Let’s create a class and spawn two threads and cause some delay in the execution if they are real threads then there will be context switchingwhile one thread is not executing another thread will execute. When start method is not called no new threads are created thus there won’t be any context switching and the execution will be sequential.

public class MyThreadClass extends Thread{
  @Override
  public void run(){
    System.out.println("In run method " + Thread.currentThread().getName());
    for(int i = 0; i < 5 ; i++){
      System.out.println("i - " + i);
      try {
        Thread.sleep(200);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
    
  public static void main(String[] args) {
    MyThreadClass mc1 = new MyThreadClass(“MyThread1”);
    MyThreadClass mc2 = new MyThreadClass();
    mc1.run();
    mc2.run();
  }
}

Output

In run method main
i - 0
i - 1
i - 2
i - 3
i - 4
In run method main
i - 0
i - 1
i - 2
i - 3
i - 4

Here two threads are created and run() method is called directly on the threads rather than calling the start() method. As you can see in the above program there is no context-switching because here threads mc1 and mc2 will be treated as normal object not thread object. Name of the thread is also not printed.

Calling start() method

Now let's change the above program and use the thread's start method rather than directly calling the run() method.

public class MyThreadClass extends Thread{
  @Override
  public void run(){
    System.out.println("In run method " + Thread.currentThread().getName());
    for(int i = 0; i < 5 ; i++){
      System.out.println("i - " + i);
      try {
        Thread.sleep(200);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
    
  public static void main(String[] args) {
    MyThreadClass mc1 = new MyThreadClass();
    MyThreadClass mc2 = new MyThreadClass();
    mc1.start();
    mc2.start();
  }
}

Output

In run method Thread-0
i - 0
In run method Thread-1
i - 0
i - 1
i - 1
i - 2
i - 2
i - 3
i - 3
i - 4
i – 4

Now you can see how context switching is happening and values are printed for both threads concurrently. You can even see the thread name printed now.

Points to note

  • When we call start() method on the thread it causes the thread to begin execution.
  • run() method of the thread is called by the Java Virtual Machine.
  • If we directly call run method it will be treated as a normal overridden method of the thread class (or runnable interface) and it will be executed with in the context of the current thread not in a new thread.

That's all for this topic What if run() Method Called Directly Instead of start() Method - Java MultiThreading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Synchronization in Java - Synchronized Method And Block
  2. Volatile Keyword in Java With Examples
  3. Is String Thread Safe in Java
  4. Livelock in Java Multi-Threading
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. equals() And hashCode() Methods in Java
  2. Fail-Fast Vs Fail-Safe Iterator in Java
  3. Nested Try Statements in Java Exception Handling
  4. Multi-Catch Statement in Java Exception Handling
  5. JVM Run-Time Data Areas - Java Memory Allocation
  6. Constructor Overloading in Java
  7. Zipping Files And Folders in Java
  8. Spring Component Scan to Automatically Discover Beans

No comments:

Post a Comment