Evidence 4 Main Thread dead after main method exits
Jeganathan Swaminathan
Greenhorn
Joined: Dec 12, 2000
Posts: 5
posted
0
Hi all, I read Maha's discussions, I found her discussions is really useful and great, but in the Threads topic i found her saying that Main thread will wait till all its child threads dies . But the program given below shows clearly contradicts, may be i'm wrong, so i want comments on this as i'm taking the SCJP2 within 2 weeks.
with regards, Jeganathan
S.Jeganathan MCA<BR>Software Engg.<BR>PSI Data Systems Ltd.,<BR>Bangalore.<BR>jeganath@psi.soft.net
Adrian Yan
Ranch Hand
Joined: Oct 02, 2000
Posts: 688
posted
0
Main thread does not wait for all children threads. Main thread by default is a daemon thread.
Ajith Kallambella
Sheriff
Joined: Mar 17, 2000
Posts: 5782
posted
0
Adrian, Main thread is not a daemon thread, it is a user thread. The main ThradGroup is not daemon either. Take a look at the following code( and read the comments ) which proves my point.
Hope that helps, Ajith
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Jeganathan Swaminathan
Greenhorn
Joined: Dec 12, 2000
Posts: 5
posted
0
I agree that main thread is not a Daemon thread but can anyone comment about Whether main thread exits when main method terminates? And thanks a lot 4 ur replies.
vadiraj vd
Ranch Hand
Joined: Dec 15, 2000
Posts: 68
posted
0
Yes Jeganathan main thread dies before the child thread in your case. I too had this confusion but after reading khalid I'm satisfied. Read page no. 273. My doubt originated from the program that I tried. Here's it. // program to demonstrate main thread dies before the child thread. class ChildThread extends Thread { Thread mainThread; ChildThread(Thread t) { mainThread = t; } public void run() { System.out.println("Main thread is alive at the start of run meth() : " + mainThread.isAlive()); try { for(int i =0;i<5;i++) { sleep(500); System.out.println("Child Thread counting : " + i); System.out.println("Main thread is alive in the run meth() : " + mainThread.isAlive()); } } catch(InterruptedException r){} System.out.println("Main thread is alive at the end of run meth() : " + mainThread.isAlive()); } } public class MainThreadIsAlive { public static void main(String a[]) { Thread t = Thread.currentThread(); System.out.println("Main thread is alive at the start of main meth() : " + t.isAlive()); ChildThread child = new ChildThread(t); child.start(); System.out.println("Main thread is alive at the end of main meth() : " + t.isAlive()); } } -vadiraj
Regards<BR>---------<BR>vadiraj<P><BR>*****************<BR>There's a lot of I in J.<BR>*****************