Java has two ways of implementing multithreading.
The first-- inherit the thread class and override the Run method
Steps:
- The definition class inherits the thread class;
- Rewrite the subclass's Run method to write the code that the thread needs to execute in the Run method;
- Creates a child class object, then creates a thread object;
- Call the object's Start method to open the thread.
Instance:
Public class extends thread () { @Override publicvoid run () { // multithreaded code } // other code }
New MyThread (); T.start ();
The second kind- implements the Runnable interface, constructs the thread class with the object of the class
Steps:
- Define class implementation runnable interface;
- Implement the Run method in the interface, write the code that the thread needs to execute in the Run method;
- Constructs a thread object with an interface object;
- Call the Start method of the thread object to open the thread.
Instance:
Public class Implements Runnable () { publicvoid run () { // multithreaded code } // other code }
Newnew Thread (m); T.start ();
Function of the Start method
- Thread was started
- Let the JVM invoke the Run method of the thread class (or subclass) object
Why are there two ways to implement multithreading?
It's easy to understand the first way. Since the run method of the thread class is overridden, the JVM invokes the Run method that the subclass overrides when the Start method is called.
For the second way, when the Start method is called, the JVM invokes the Run method of the thread class with the following code:
Public void run () { ifnull) { target.run (); }?}
Where target is the member variable of the thread class, and the type is runnable. When you construct a thread with a Runnable object, the target references that interface object, so when you execute Target.run (), the Run method of the interface object is actually executed.
Use of Java Multi-threading