2

Better Post : "implements Runnable" vs. "extends Thread"

I can create my own thread class MyThread two ways,

class MyThread extends Thread
or
class MyThread implements Runnable

Which technique is better and why?

And in case of implementing Runnable, I have to create Thread object from MyThread object, like

MyThread mt = new MyThread();
Thread t = new Thread(mt);

then what is the advantage of implementing Runnable Interface technique?

Community
  • 1
  • 1
Denim Datta
  • 3,740
  • 3
  • 27
  • 53

3 Answers3

4

While creating a thread implementing Runnable interface is better. Because you can extend your new class from other class, otherwise you can not extend it.

Ugur Artun
  • 1,744
  • 2
  • 23
  • 41
0

Extending a Thread is better if you want to retain some control over the thread's work, like calling interrup(). In general, I'd say that extending a Thread is OK when the class is some kind of Manger or Worker.

In other cases, especially when a class represents some work to be done (Job, Future) it's much better to implement runnable.

Dariusz
  • 21,561
  • 9
  • 74
  • 114
0

And in case of implementing Runnable, I have to create Thread object from MyThread object, like

MyThread mt = new MyThread();
Thread t = new Thread(mt);

NOT NECESSARILY

You can do this...

Thread t = new Thread(new Runnable () { public void run() { /* do stuff */ }});

... no need for MyThread class.

xagyg
  • 9,562
  • 2
  • 32
  • 29