This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
In some mock exams I have noticed thread is started by calling only start() and not Th.start()(where th is the thread instance) .I also tested with some examples this works if a class extends thread but not if class implements runnable.
Does that mean if class extends thread , we can just use start () method to start a thread
Hi Smitha, As Marc said any instance of that class will be a thread & will have an "implicit" reference 'this' to all instance members. Its not mandatory in such a situation to use 'this' you can call directly as well. 'this' is generally used to differentiate between a local variable & the field which it hides or shadows.Therefore,this.start(); & start() will have the same meaning in this context.
Smitha, it depends whether you observered the call to start() in an instance method of the class which extends a thread or in the main method. I'm sure code you are referring is inside an instance method and this should make clear what marc is trying to explain.
It is always makes things easy, if you can post the code.
Originally posted by Smitha Ballikar: ...this works if a class extends thread but not if class implements runnable...
Note that Runnable is an interface with a single method, public void run(). The Runnable interface does not contain a "start" method. So if an object's reference type is Runnable, then start() cannot be called on that object.
The Thread class implements Runnable, providing implementation for the run() method. In addition, Thread defines a start() method. So if an object's reference type is Thread, then both start() and run() are available as methods.
(Of course, calling run() directly will execute that method's body in the current thread, instead of as its own thread.)