Originally posted by Anto telvin Mathew:
hi all
what is the relationship between Thread class and Runnable Interface ?Why it is not necessary to create a Thread object for creating Threads if we are extending it.But if we are implementing it we have to explicitly create an Object of Thread.so what make this difference ?
The answer is simple watch the API Specification :
public class Thread extends Object implements Runnable
To be more precise :
Remember :
To make a thread object you have to say
Thread objThread = new Thread(anyobject of type class that implements runnable);
To execute that object as a thread say
Thread.start();
will internally call run() method;
This is the way to create and start a thread !
The Class Thread has a constructor of version
Thread(Runnable target)
Allocates a new Thread object.
The interface Runnable has a method run()
The part of code inside run() will be considered as a single unit of execution.
Why it is not necessary to create a Thread object for creating Threads if we are extending it.
If you extend it implicitly extends thread and implements Runnable
Where the run() method is implicitly available.
Just say Object.start(); //will call run internally
Thats why creating a class that extends thread need not explicitly need to create a thread object .
You are making the object to be a thread - there itself !
if we are implementing it we have to explicitly create an Object of Thread.so what make this difference ?
If you implement Runnable, you say that the object capable to run as a Thread.
So you have to pass it to the Thread Constructor - Thread(Runnable)
Then, the Thread would consider and execute this object as a Thread.
Invoiking the run() method internally !
so what make this difference ?
In both cases you have to Implement Run() method(Mandatory)Without calling .start on an object - Thread will not start !I can give an example, but try yourself with the information.else, you will not know the difference by yourself !Implementing through Runnable is the best way.See tutorial pages of sun
Hope this helps !
[ October 15, 2008: Message edited by: ram kumar ]