We Call Java Run() Method Directly Instead Start() Method - Java Tutorial

We Call Java Run() Method Directly Instead Start() Method

BLUF: Mastering We Call Java Run() Method Directly Instead Start() Method is a key requirement for any Java developer. This lesson breaks down the object-oriented principles and syntax required to use this concept in real-world applications.
Write Once, Run Anywhere Tip: We Call Java Run() Method Directly Instead Start() Method

Java's versatility is unmatched. Learn how We Call Java Run() Method Directly Instead Start() Method fits into the Java ecosystem and improves your code structure in the tutorial below.

  • Each thread starts in a separate call stack.
  • Invoking the run method from the main thread, the run method goes onto the current call stack rather than at the beginning of a new call stack.

FileName: TestCallRun1.java

Example

class TestCallRun1 extends Thread{
 public void run(){
   System.out.println("running...");
 }
 public static void main(String args[]){
  TestCallRun1 t1=new TestCallRun1();
  t1.run();//fine, but does not start a separate call stack
 }
}

Output:

Output

running...

Problem if you direct call run method

FileName: TestCallRun2.java

Example

class TestCallRun2 extends Thread{
 public void run(){
  for(int i=1;i<5;i++){
    try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
    System.out.println(i);
  }
 }
 public static void main(String args[]){
  TestCallRun2 t1=new TestCallRun2();
  TestCallRun2 t2=new TestCallRun2();
 
  t1.run();
  t2.run();
 }
}

Output:

Output

1
2
3
4
1
2
3
4

In the program shown above, it is evident that there is no context-switching occurring since t1 and t2 are considered regular objects and not thread objects.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience