Two ways to implement multithreading in java

There are two ways to implement multithreading in java: inheriting the Thread class and implementing the Runnable interface
(1) Inherit the Thread class to create multiple threads
1) Define a subclass of the Thread class and rewrite the run method, changing the run method to represent the task to be completed by the thread
2) Create a thread object and call the start() method to start the thread
Features: The thread class has inherited the Thread class and cannot inherit other parent classes
(2) Implement the Runnable interface
1) Define the implementation class of the Runnable interface and override the run() method of the interface
2) An instance of the common Runnable interface implementation class, then create a Thread object and call the start() method
Features: Create multiple threads by implementing interfaces. These threads can also inherit other classes. Multiple threads can share the same object, which is suitable for multiple threads to process the same resource, so that the CPU, code and data are separated. The structure is relatively clear. In most cases, you will choose to implement the Runnable interface.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325940874&siteId=291194637