Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What is difference between Extending Thread and Runnable Interface  RSS feed

 
Sudhir Kumar Ojha
Greenhorn
Posts: 13
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everyone

i am practicing multithreading today and i want understand

What is difference between Extending Thread and Runnable Interface and which one is better.
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should know Java can only inherit (extend) one class, while can implement multiple interfaces. Runnable is an interface. So base on this alone, the "implements Runnable" is the preferred choice.

Furthermore, the "extends Thread" creates its own unique instance variables every time, while "implements Runnable" does not.

A more detailed explanation with example here
 
Stephan van Hulst
Saloon Keeper
Posts: 7802
142
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a bit of a special case though, because it was a huge design mistake to make Thread Runnable in the first place. Tasks should be runnable, and a thread does not represent a task. Instead, a thread is what runs a task.

That means that in the past, the best way was to create a Runnable that represents your task, and pass it to a Thread constructor.

Nowadays though, you should not be touching the Thread class at all. Instead, pass your Runnable to ExecutorService.submit().
 
Sudhir Kumar Ojha
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great man its work
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!