Java implements multithreading in two ways: inheriting the thread class and implementing the runnable interface
What is the difference between implementation and inheritance@ H_ 404_ 5@
*Difference: @ h_ 404_ 5@
*Inherit thread: the thread code is stored in the run method of thread subclass @ H_ 404_ 5@
*Implement runnable: the thread code is stored in the run method of the subclass of the interface @ h_ 404_ 5@
*Benefits of implementation: avoid the limitations of single inheritance @ h_ 404_ 5@
*When defining threads, it is recommended to use the implementation method. Of course, if a class does not inherit the parent class, you can also inherit the thread class to implement multithreading @ H_ 404_ 5@
*Note: if the runnable interface does not throw an exception, the class implementing it can only be try catch, not try catch throws@H_404_5 @
*Java provides a professional solution to the security problem of multithreading, which is to synchronize the code block synchronized (object) {code to be synchronized} @ H_ 404_ 5@
*Prerequisite for synchronization: @ h_ 404_ 5@
*1. There are 2 or more threads @ H_ 404_ 5@
*2. Multiple threads use one lock (object) @ h_ 404_ 5@
*Benefits of synchronization: it solves the security problem of multithreading @ H_ 404_ 5@
*Disadvantages of synchronization: multiple threads need to determine locks, which consumes resources @ H_ 404_ 5@
The above are the two ways to implement multithreading in Java brought by Xiaobian. Inherit the thread class and the methods to implement the runnable interface. I hope it will be helpful to you and support more programming tips ~ @ H_ 404_ 5@