aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Interesting Ques in Threads????? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply locked New topic
Author

Interesting Ques in Threads?????

Harpal Singh
Ranch Hand

Joined: Oct 10, 2000
Posts: 229
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

Joined: Mar 17, 2000
Posts: 5782
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


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
amit shukla
Ranch Hand

Joined: Oct 25, 2000
Posts: 45
refer khalid's first two pages of multithreading chapter..it'll be clear then..
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
Let the discussion continue here....an identical post from the same author!
Ajith
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Interesting Ques in Threads?????