Ashok ,
good question ! nice
well.. the the reason to seemingly-strange output of above code lies in two factors ;
- The way Thread's start() n run() hav been implemented
-
Polymorphism n inheritence
The Thread class start() method is native , all it does is it will instruct JVM to spawn a new-thread in which to run the run() method of this thread .
Now carefully look below at the way run method has been implemented ;
public void run() {
if (target != null) {
target.run();
}
}
(
target is the one which we pass as
Runnable in Thread's constructor )
All i mean to say is that start() method just calls the run() method , it
DO NOT checks whether a Runnable was passed or not , and if was passed then to call Runnable's run() method instead of Thread's run method , somehow by design-choice , this functionality has been kept in run() method of Thread, instead of start().
Now , when we
extends Thread class , and
override run() method , wht we get is a class with ;
-start() method inherited from parent Thread()
-run() method of its own
A call to start() method on object of such a class , obviously spawan a new Thread with overriden run() method
( explanation to this lies in the property of Polymorphism , inheritence n method lookup tht is )
To make things understandable ( n experimentable , u cant bother to change original Thread implementation!
) , i have wrriten following code ,
Most of the hierachy corresponds to original thread classes , but i hav kept them simple according to our specific problem
not surprisingly , the output of above code is :
Doing YourWork In bare-bones ,all wht-is-happening is due to design-choice , if instead of keeping runnable-check functionality in run() method (doing the target==null check n then calling its run) , if it wuld hav been kept in start() method , then result will hav been altogether diff.
Like in my code if we change start() n doit() method in Work class as :
public void start() { if(work != null) work.doit(); else doit(); }
public void doit() { /* do nothing */ } ;
The the output changes to :
Doing MyWork Read this code once or twice , n try to experiment it for urself , n i am sure , u ll get my point.
BTW , it is pity tht there are no marks in
SCJp for asking questions !
otherwise i wuld hav whole heartily given Ashok full marks !
nice question , keep discussing these kinda things
have chillin preparation n Good Luck !
[This message has been edited by Gagan Indus (edited September 09, 2001).]