Difference between Thread and Runnable in Java

The Thread class is the Java language's abstraction of threads.

Runnable is an abstraction of tasks and an abstraction of business logic

In addition, Thread actually implements the Runnable interface, which is an extension of Runnable.

Which is better than implementing Runnable and inheriting Thread?

a. From the code point of view, Java can only inherit single but can be implemented multiple times, Runnable is better

b. From the perspective of scalability:
Inheritance mode, thread objects and tasks are tightly coupled together.
Implementation mode, thread objects and task objects are separated, the coupling is low, and the scalability is high

It is suitable for multiple threads of the same program code to process the same resource; this is to avoid the limitation of single inheritance in Java, increase the robustness of the program, the code can be shared by multiple threads, and the code and data are independent. The thread pool can only be put into the thread that implements the Runnable class, and cannot be directly put into the class that inherits Thread.
In summary: The implementation is better

Guess you like

Origin blog.csdn.net/qq_41489540/article/details/109109699