Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 'extends Thread' exist, when 'implements Runnable' is winner in all cases [duplicate]

I know that implements Runnable is preferred over extends Thread in Java threads as it allows us to extend some other class if it is required. But if this is the case, does extends Thread also have its own advantages over implements Runnable and if so, what are these advantages?

like image 311
rahul Avatar asked Jan 22 '16 11:01

rahul


People also ask

Why is it preferred to implement runnable instead of extending thread?

When we extend Thread class, we can't extend any other class even we require and When we implement Runnable, we can save a space for our class to extend any other class in future or now.

Can we extend thread and implement runnable at the same time?

OK, but you can't extend the Thread class without creating a Runnable because Thread is Runnable. The real choice is, do you extend the Thread class, or do you create a base Thread instance and give it a Runnable delegate.

Why do we extend thread class?

Create a Thread by Extending a Thread Class This approach provides more flexibility in handling multiple threads created using available methods in Thread class.

Why isn't thread class Final Why would I extend thread ever?

They cannot make it final , however, because that would break backward compatibility. As far as practical reasons go, I think the only reason you may want to extend Thread rather than implement Runnable today would be to override its methods other than run() .


2 Answers

Because sometimes (almost never, but sometimes) you want to be able to change the basic behaviour of Thread.

That's when you'll need to extend it.

You can change it by overriding a method from the Thread class, you can't do it by implementing one from Runnable.

like image 149
Stultuske Avatar answered Oct 05 '22 23:10

Stultuske


In the last 20+ years since Java 1.0 was released, what is a considered a good design pattern has changed. However, Java is committed to backward compatibility which means old code which might use poor design patterns will still work.

One of my pet hates is StringBuffer for which it was never a good idea to make it's method synchronized, was replaced more than tens years ago, but unfortunately developers are not prevented from using it today and even new developers use it, even though it was deprecated long before they started using Java.

like image 36
Peter Lawrey Avatar answered Oct 06 '22 01:10

Peter Lawrey