Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread & runnable

 
Shailesh Narkhede
Ranch Hand
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is difference between Implementing Runnable & extending Thread class.

one I know,
Java not support multiple Inheritance so If our class is extending any other class and we need to extend that class from Thread class,then it is not possible in this case we are Implementing Runnable interface.
correct me If I am wrong.

Is there any other difference between Implementing Runnable & extending Thread class?

Please explain with scenario.


Thanks In advance.
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java not support multiple Inheritance so If our class is extending any other class and we need to extend that class from Thread class,then it is not possible in this case we are Implementing Runnable interface


Yes. That's a an important scenario for using Runnable over extending Thread. And By using Runnable it's easy to seperate the logic to be run in a seperate thread from the thread itself.
 
Shailesh Narkhede
Ranch Hand
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By using Runnable it's easy to seperate the logic to be run in a seperate thread from the thread itself.


Vijitha Kumara,

can you please put more light on this ?
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you are not messing the runnable code (which is inside the Runnable implementation) with the Thread which actually runs the code. So the logic is seperated from other code,easy to change and manage.
 
Shailesh Narkhede
Ranch Hand
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got some what but still not clear idea of that


 
karan khosla
Greenhorn
Posts: 25
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok. Here is the Scenario, Suppose your class extends Thread class and does not provide run() method the compiler or the runtime will not give any errors or warnings and the bytecode runs successfully. Whereas, if you implements Runnable interface which is always the best choice (recomended) you get an compile-time error something saying your class does not override run() method or simply declare your class as abstract.

The most important thing to note here

if you inherit from a class you are doing specialization of the parent implementation, whereas, if you inherit from an interface you have to provide the implementation ourself of all the method specified in that interface.

I Hope this information will help you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic