AdSense

AdSense3

Saturday, 27 September 2014

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. }  
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.    
  12.   t1.run();  
  13.   t2.run();  
  14.  }  
  15. }  
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.

No comments:

Post a Comment