April 30, 2008
Open Question: Java experts :Please answer this question?
class NewThread extends Thread
{
NewThread()
{
Thread t=new Thread("Demo Thread");
System.out.println("Child Thread "+this);
start();
}
public void run()
{
try
{
for(int i=5;i>0;i--)
{
System.out.println("Child Thread "+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("Child Interrupted");
}
System.out.println("Existing Child Thread");
}
}
class ExtendThread
{
public static void main(String[] args)
{
NewThread th=new NewThread();
try
{
for(int i=5;i>0;i--)
{
System.out.println("Main Thread "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("Main thread exiting");
}
}
I want to ask that in the NewThread constructor,when I write t.start();,child thread doesn't execute.When I write,start(),its fine.Why?
And in line-System.out.println("Child Thread "+this);,'this' shd return memory location of th.Instead it returns the thread name.Why?