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
posted
0
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
posted
0
refer khalid's first two pages of multithreading chapter..it'll be clear then..
Ajith Kallambella
Sheriff
Joined: Mar 17, 2000
Posts: 5782
posted
0
Let the discussion continue here....an identical post from the same author! Ajith