1. Inheriting the thread class
- Defines a class that inherits the thread class.
- Override the Run method.
- Instantiate the subclass object, call the Start () method, and call the Run method.
2. Implement the Runnable interface
- Defines the class implementation runnable interface.
- Overwrites the Run method in the interface, encapsulating the thread's task code into the Run method.
- The thread object is created through the thread class and the subclass object of the Runnable interface is used as a parameter to the constructor of the thread class. Because the task of the thread object is encapsulated in the Run method of the Runnable interface subclass object, you must explicitly define the task to run when you create it.
- Invokes the start () method of the Thread object.
The second method is more commonly used:
- Separate the subclass tasks into separate packages.
- Avoids the limitations of Java single inheritance.
Java-two ways to create a thread