Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Evidence 4 Main Thread dead after main method exits

 
Jeganathan Swaminathan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Adrian Yan
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Main thread does not wait for all children threads. Main thread by default is a daemon thread.
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeganathan Swaminathan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic