«Back to Home

Core Java

Topics

Call run() Method Directly Instead Of start() Method

If we call run() method directly instead of start() method

Every thread starts in a separate call stack.
 
Calling the run() method from the main thread, followed by the run() method goes on the present call stack rather than at the beginning of a new call stack.
 
Let’s understand with the example, given below.
 
Code
  1. public class Car extends Thread {  
  2.     public void run() {  
  3.         System.out.println("Honda car is running...");  
  4.     }  
  5.     public static void main(String args[]) {  
  6.         Car t1 = new Car();  
  7.         t1.run();  
  8.     }  
  9. }  
11

Output

12

In the above example, we observe that program run normally but it does not start a separate call stack.
 
Let’s see another example, given below, if we directly call run() method.
 
Code
  1. public class Car extends Thread {  
  2.     public void run() {  
  3.         for (int i = 0; i < 7; i++) {  
  4.             try {  
  5.                 Thread.sleep(500);  
  6.             } catch (InterruptedException e) {  
  7.                 System.out.println(e);  
  8.             }  
  9.             System.out.println(i);  
  10.         }  
  11.     }  
  12.     public static void main(String args[]) {  
  13.         Car t1 = new Car();  
  14.         Car t2 = new Car();  
  15.         t1.run();  
  16.         t2.run();  
  17.     }  
  18. }  
13

Output

14

In the example, mentioned above, we can see, there is no context-switching because here t1 and t2 will treat as a normal object and not a thread object.
 
Summary
 
Thus, we learnt, if we call run() method directly instead of start() method, object treats it as a normal object and not a thread object in Java multithreading.