Java provides threading class thread to create multithreaded programs. In fact, creating a thread is the same as creating an object of a normal class, and a thread is an instance object of the thread class or its subclasses. Each thread object describes a separate thread. To produce a thread, there are two ways of doing it:
You need to derive a new thread class from the Java.lang.Thread class, overloading its run () method;
Implement the Runnalbe interface, overloading the run () method in the Runnalbe interface.
Why should Java provide two ways to create threads? What are the differences between them? In comparison, which method is better?
In Java, a class only supports single inheritance, that is, when a new class is defined, it can only extend one external class. This way, if the custom thread class is created by extending the thread class, then the custom class cannot extend the other classes. It is not possible to implement more complex functions. Therefore, if your custom class must extend other classes, you can define the class as a threading class by using a method that implements the Runnable interface, which avoids the limitations of Java single inheritance.
It is also important that threads created with the implementation of the Runnable interface can handle the same resource, thus sharing resources.
Two ways to create a thread in Java