Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference b/w extending Thread and implementing an interface

 
Sathish Kumar Govindan
Greenhorn
Posts: 18
Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers,
Please tell me the difference b/w extending Thread and implementing an interface.By using Both the ways we can implement the thread concept. so, i want to Know at what circumstance i have to use them....
If i am extending the thread, then i can't extend one more class. Apart from this reason is there anything......


Thanks in Advance,,
G.sathish Kumar.
 
John Bartlett
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I do not beieve there is any difference between the two apart you are only allowed to extend one class so if you extend thread you would not be able to extend anything else.

This is why implement runnable is probably the best option.

Quote found:

"If you're considering having your class extend Thread ask yourself, "Have I invented a new kind of thread, or do I simply have something that executes in a thread?". If it's the latter (and it usually is) then you should strongly consider implementing Runnable instead.

There are a few reasons for this. The first is mainly aestheic. The extends & implements keywords denote an "is a" relationship. Extending Thread declares that your class is a new kind of light-weight process. On the other hand, implementing Runnable declares that your class is a task that can execute in a thread. In other words, it's not the process itself, but rather what the process is doing. The distinction is subtle but it can be important.

There are practical reasons too. For one thing, extending Thread means that you cannot extend anything else. If you MUST extend from another class then you'll have to implement Runnable instead.

Also, several methods in the Thread class are synchronized. If you declare synchronized methods in your Thread subclass then you run the risk that they will interfere with the normal thread functions. You might even encounter a deadlock. It's safest to avoid synchronizing on the same object for two different purposes.

A good rule of thumb is to always implement Runnable and extend Thread only if you have a very good reason. If you think about it, I think you'll find very few reasons not to implement Runnable."

Hope this helps,

John
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also see this FAQ entry: ExtendingThreadVsImplementingRunnable
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic