What does this mean by separating the task from the thread?

I am reading Java multithreading programming. The java book says that separating the task from the thread is the preferred design. I have no idea what this means.

From what I understand, it is better to use Runnable utilities instead of continuing with Threads. I just don't understand why this is the case.

Why is adoption better than expanding? And when will you use the extension, then?

+3


source to share


3 answers


An important principle in software development is separation of concerns: each module / object / class / method should only have one clearly defined responsibility.

The Thread class confuses two issues:

  • setting a sequence of steps to be performed (Runnable)

  • interacting with the runtime system to control how to implement the execution of this sequence (in this case using a dedicated CPU thread)



The programmer-programmer doesn't have to worry about the second part: she just needs to write the code she wants to execute, i.e. implement Runnable.

This Runnable can be executed in several ways, for example by starting a new thread, but also by providing it to the ExecutionService. This flexibility disappears when you hardcode your runnable into Thread.

+4


source


The advantage Runnable

is that you can pass Runnable

to things other than the constructor Thread

. For example, you can use them in combination with new concurrency frameworks.



One of the reasons you might want to extend Thread

is because your task requires direct access to the object Thread

in which it runs.

+3


source


Logically, the IS-A relationship should not be about composition.

Thus, extending the Thread class is "useful" when you want to create your own thread that will be useful for all super-methods or override certains methods => In this case, for the Thread class, it is mostly useless.

Also, Extending Thread prevents you from extending the required business class, while with the interface you can still go from the desired class.

We always need to ask ourselves whether a new class needs a concept or an IS concept.

NEEDS Thread for business class, so it can separate it from the whole concept of Threading => So Runnable enough light to mask it.

0


source







All Articles