Reputation: 191
I am reading up on multi-threaded programming in Java. In the java book it says separating the task from the thread is a preferred design. I have no idea what this means.
From what I understand it is better to use implements Runnable instead of extending Threads. I just don't understand why this is.
Why is implementing better then extending? And when would you use extending then?
Upvotes: 3
Views: 189
Reputation: 22191
Logically an IS-A relationship shouldn't deal with a concept of composition.
So, extending Thread Class are "useful" when you want to create a custom Thread, that benefit of all super methods or override certains methods => In this case for a Thread class, it's certainly useless for most cases.
Furthermore, extending Thread prevents you to extend a needed business class for instance whereas with an interface, you can still extends from the class you desire.
We always have to wonder if the new class NEED a concept or IS the concept.
You NEED Thread for Business class , so it's likely to separate it from all Threading notion => So Runnable is enough light for masking it.
Upvotes: 0
Reputation: 262774
An important principle in software design is separation of concerns: Every module/object/class/method should have only one well-defined responsibility.
The Thread class mixes two concerns:
specifiying a sequence of steps to be executed (the Runnable)
interacting with the runtime system to manage how to implement execution of that sequence (in this case by means of a dedicated CPU thread)
An application programmer should not need to concern himself with that second part: She should just need to write down a code path that she wants executed, i.e. implement a Runnable.
That Runnable can then be executed in a number of ways, for example by starting a new Thread, but also by giving it to an ExecutionService. This flexibility goes away when you hard-code your runnable into a Thread.
Upvotes: 4
Reputation: 25676
The advantage of Runnable
is that you can pass a Runnable
to things other than the Thread
constructor. For instance, you can use them in conjunction with the new concurrency frameworks.
One reason you might extend Thread
is if your task needs direct access to the Thread
object that it's running in.
Upvotes: 3