I got this as an interview question.
why isn't Thread class final? Why would you extend a Thread ever?
I could not come up with real world use cases.
From Oracle's documentation:
There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. The other way to create a thread is to declare a class that implements the Runnable interface.
So the answer is "you may want to subclass Thread
to override its run()
method."
The quoted paragraphs have been in the Java documentation going back as far as JDK 1.1. Java has added other convenient classes for managing concurrency, most notably, the executors mentioned in the comments, possibly diminishing or eliminating the need to extend Thread
. 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()
. For example, you may want to add logging or additional clean-up.
This is pretty much just taken from John Vint's comment, but I think it's the best answer.
The only time I can think of where I might extend Thread
rather than implementing Runnable
-- or, even better, just using an ExecutorService
with a Future
-- is when I needed to override Thread.interrupt()
to do some cleanup. Otherwise, I can't see any practical reason to actually extend Thread
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With