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?
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.
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.
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