wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes start() method in Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "start() method in Thread" Watch "start() method in Thread" New topic
Author

start() method in Thread

ritwik roy
Greenhorn

Joined: May 13, 2005
Posts: 20
hai all
i have a doubt regarding the start() method of Thread class. start() implicitly calls the run() method of that class. o.k
but what is the problem if i override the start().
why in my follwing code after completing the start method in PrintNumThread
class the control fails to go to the run() method ???
plz clarify.
ritwik


class TestThread
{
public static void main(String arg[])
{
PrintNumThread pnt=new PrintNumThread();
pnt.start();
}
}
class PrintNumThread extends Thread
{
public void start()
{
System.out.println("PrintNumThread Started");

}
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(i);
}

}
}
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

why in my follwing code after completing the start method in PrintNumThread class the control fails to go to the run() method ???

It fails precisely because you've overridden the start method with the behavior you specify.
Sherry Jacob
Ranch Hand

Joined: Jun 29, 2005
Posts: 128
Hi ritwik,
Well, the problem is this. Overridden method calls are always resolved at runtime based on the object which calls the method.

You have declared an object of the PrintNumThread class in the main() method as :


So, pnt is the object. Had you not overridden the start() method, the default action of pnt.start() would be to call the run() method of the PrintNumThread class.

However, since you have overridden the start() method in the PrintNumThread class, so at runtime, the object pnt would call the new overridden start() method and not the default start() method.

That's why the control does not reach the run() method since your overridden start() has only one statement:


Hope this helps !!


<strong><br />Cheers !!<br /> <br />Sherry<br /></strong><br />[SCJP 1.4]
ritwik roy
Greenhorn

Joined: May 13, 2005
Posts: 20
thanks Steve and sherry.
My doubt is cleared. But why then in java API the start() method has not
been declared final??
we know final method can't be overriden and in this type of case we must not override the start() method, so it should have been declared final.
what do u think???
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: start() method in Thread
 
Similar Threads
Thread Doubt
Thread: start() and run() defined, which one happens?
Thread
Threads doubt??
extends Thread.........