Tyson
Tyson

Reputation: 13

what is the behavior of start method inside run method while multithreading in java

What happens exactly when we create a new thread and start it in the run method itself? Why do I get different behavior when I declare the thread inside or outside of the run method? Following is the example that I tried:

   class MyTDemo implements Runnable {  
     // If I declare t2 here, the program ends after some time
     // Thread t2; 
 public void run()        
  { 
      // If I declare t2 here, the program never ends (until StackOverFlowException)
      Thread t2; 
      System.out.println("in Run");     
      t2 = new Thread(this);     
      try{        
           t2.sleep(5000);   
           t2.start();   
           System.out.println("going out "+t2.isDaemon());       
           t2.sleep(5000);        
           t2.setDaemon(true);           
        }      
      catch(Exception e){System.out.println(e.getMessage());} 
}       
    public static void main(String args[])    
{   
      MyTDemo t = new MyTDemo();     
      Thread t1,t2;    
  t1 = new Thread(t);     
      t1.start();          
      System.out.println("End");        
 }
}

Upvotes: 1

Views: 89

Answers (2)

Markus Malkusch
Markus Malkusch

Reputation: 7868

You are starting threads recursively. MyTDemo is starting in its run() method a new MyTDemo thread.

Upvotes: 3

assylias
assylias

Reputation: 328608

  • In one case you call t2.setDaemon(true); on the local t2 variable after the next thread has been started. So you always have at least one non-daemon thread running and that prevents the program from exiting.

  • In the other case, you set the the daemon status on the shared t2 variable which allows the program to exit if that statement is executed before the next thread is started, which randomly happens after a few runs.

You could add a System.out.println("is daemon: " + t2.isDaemon()); after t2 = new Thread(this); to better see what is going on.

Upvotes: 2

Related Questions