I've tried creating various constructors for MyThread, and I've looked at the Thread source code trying to understand, but I haven't been able to figure out why it works for Thread but not for MyThread. I
Constructors are not inherited. Your MyThread class only defines one no-argument constructor. The compiler can't find any other constructor that it can match to your attempt to instantiate MyThread with a lambda expression. You need to declare a MyThread constructor that takes a Runnable as its argument if you want to do that.
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
Here's a question back: why extend Thread? What functionality would you like to add that isn't already present?
Extending Thread just to override the run method is unnecessary as you can give a Runnable to the constructor. A Runnable instance is reusable (can be used in multiple threads), a Thread instance can only be started once. And since Java 8 it's even easier to use a lambda for a Runnable, whereas if you extend Thread you must be as verbose as always:
As Junilu pointed out in his very helpful answer, this is equivalent to declaring an anonymous Runnable. Even if I had declared an explicit Runnable, I'd still have to spin up a thread to run it.
And yes, I do know about Futures and Callables and ThreadPoolExecutors. But that wasn't the question I asked. I have looked at the web trying to get an answer to the Thread vs Runnable question, and despite special pleading for Runnables as "preserving the option to inherit from other than class Thread", and "Runnables can be reused" there are lots of times when these just aren't an issue. As far as I can tell, it boils down to personal preference.
Stephan van Hulst
posted 9 months ago
Well yes, it's personal preference. Take a look at the following application:
Why did I extend Rectangle? You might chalk it up to my eccentric preference to make everything fit in boxes. Similarly, there's never a good technical reason to extend Thread; it only serves to confuse programmers that don't share the same preference.
No application IS a rectangle. No runnable task IS a method of execution of said task.
posted 9 months ago
That is actually the best and clearest explanation I have ever heard.
Yes, my master! Here is the tiny ad you asked for:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop