Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Main Thread is Alive ?

 
Vadiraj Deshpande
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
Here is a program which says main thread dies before the child thread. Is that happening in reality ?
check this out --
regards
vadiraj
----------------------------------------------
class NewThread implements Runnable
{
String name;
Thread t,mainThread;
NewThread(Thread mainThread,String tname)
{
name=tname;
this.mainThread=mainThread;
t = new Thread(this,name);
System.out.println("New Thread : " + t);
t.start();
}
public void run()
{
System.out.println("Main Thread is Alive in the start of run meth of "+name+" : " + mainThread.isAlive());
try
{
for(int i=3;i>0;i--)
{
System.out.println(name + ": " +i);
System.out.println("Main Thread is Alive in the run meth of "+name+" Thread : " + mainThread.isAlive());
Thread.sleep(1000);
}
} catch(InterruptedException e)
{}
System.out.println(name + " Exiting");
System.out.println("Main Thread is Alive in the end of run meth of "+name+" Thread : " + mainThread.isAlive());
}
}
public class MainThreadisAlive
{


public static void main(String a[])
{
Thread t=Thread.currentThread();
System.out.println("Main Thread : " + t);
NewThread child1 = new NewThread(t,"Thread1");
NewThread child2 = new NewThread(t,"Thread2");
int i=0;
try
{
for(i=0;i<5;i++)
{
t.sleep(100); // Sleep time is less than the sleep time of the child threads.
System.out.println("Main Thread: " + i);
}
} catch(InterruptedException e)
{
}
System.out.println("Exiting main Thread");
System.out.println("Main Thread is Alive in the end of main: " + t.isAlive());
}
}
------------------
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic