Win a copy of Design for the Mind this week in the Design forum!
    Bookmark Topic Watch Topic
  • New Topic

Interesting Ques in Threads?????

 
Harpal Singh
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Report post to moderator
Dear Guys,
Below is a simple programme.....
class FunnyThreads implements Runnable
{
public void run()
{
try
{
for(int i =0;i<3;i++)
{
System.out.println("Child threads "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{}
System.out.println("exiting child");
}
public static void main(String[ ] args)
{
FunnyThreads ft = new FunnyThreads();
Thread t = new Thread(ft);
t.start();
try
{
System.out.println("Main thread");
Thread.sleep(500);
}
catch(InterruptedException ie){}
System.out.println("Main Exiting");
}
}
According to some books Like Complete refrence(Patrick)...The main should exit at last else the system will hang...and moreover I think after Main exits there should not be further execution of the programme.....And here is the out put of above programme....
---------- run ----------
Main thread
Child threads 0
Main Exiting
Child threads 1
Child threads 2
exiting child
Normal Termination
Output completed (4 sec consumed).
------
here main() has exited long back...but there is normal termination of the programme.....
CAN SOMEBODY EXPLAIN ME WHY IS THIS SO???
INTRESTING HUH!!!
Thanks,
Harpal
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Report post to moderator
This is the way it is!!
Remember, when the main method exits, the JVM may or may not exit. The JVM exits only when there are no user threads running. In your program, the main method creates several user ( non-daemon ) threads. Since the threads represent asynchronous path of execution, they continue to run even after the parent thread( main method ) terminates.
Just make your FunnyThreads objects daemon( use setDaemon ) and see what happens
Ajith
 
amit shukla
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Report post to moderator
refer khalid's first two pages of multithreading chapter..it'll be clear then..
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Report post to moderator
Let the discussion continue here....an identical post from the same author!
Ajith
 
    Bookmark Topic Watch Topic
  • New Topic