0

We can declare thread in class using two ways

  1. extends Thread class
  2. implements Runnable interface

so which scenario is the best way?

Sasikumar Murugesan
  • 4,412
  • 10
  • 51
  • 74

2 Answers2

0

There is no "best", they're both good. There is most appropriate, though.

For over 90% of the cases, implementing Runnable is the way to go. You should never extend Thread, unless you need to change the functionality provided by the Thread class.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
0

You should implement Runnable, since you can extend only one class, and you might want to use it to extend something that cannot be implemented.

Sandeep Kaul
  • 2,957
  • 2
  • 20
  • 36
  • yes but we can extends Thread class in super class. am i right? – Sasikumar Murugesan May 08 '15 at 18:49
  • 1
    You can, there is nothing wrong with it, but it's just better to implement Runnable, in-case you might want to extend something now or later. It's just about following a practice. – Sandeep Kaul May 08 '15 at 18:51
  • Sasikumar: Thread IS that superclass. – Stultuske May 08 '15 at 18:52
  • There's a better way to say that. The `r` in `new Thread(r)` becomes the thread's _delegate_. Using _delegation_ generally is a more powerful, more flexible way to structure a program than using inheritance. It often makes code easier to test, and easier to modify. – Solomon Slow May 08 '15 at 21:10