What if we call run() method directly instead start() method?

What if we call run() method directly instead start() method?

  • Each thread starts in a separate call stack.
  • Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
  1. class TestCallRun1 extends Thread{
  2.  public void run(){
  3.    System.out.println(“running…”);
  4.  }
  5.  public static void main(String args[]){
  6.   TestCallRun1 t1=new TestCallRun1();
  7.   t1.run();//fine, but does not start a separate call stack
  8.  }
  9. }

Test it Now

Output:running...

MainThreadStack Problem if you direct call run() method

  1. class TestCallRun2 extends Thread{
  2.  public void run(){
  3.   for(int i=1;i<5;i++){
  4.     try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
  5.     System.out.println(i);
  6.   }
  7.  }
  8.  public static void main(String args[]){
  9.   TestCallRun2 t1=new TestCallRun2();
  10.   TestCallRun2 t2=new TestCallRun2();
  11.   t1.run();
  12.   t2.run();
  13.  }
  14. }

Test it Now

Output:1
       2
       3
       4
       5
       1
       2
       3
       4
       5
As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not thread object.
java for beginners
java for beginners
java for beginners
CodSir //course // books
...

WikiSir

What if we call run() method directly instead start() method? Each thread starts in a separate call stack. Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack. 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  } } Test it […]

Tags:

....
...