Java multithreading and Java Multithreading
Java supports multithreading in two ways.
First -- Inherit the Thread class and override the run Method
Steps:
Instance:
Public class MyThread extends Thread () {@ Override public void run () {// multithreading code} // other code}
Thread t = new MyThread();t.start();
Second: implement the Runnable interface, and construct the Thread class with the object of this class.
Steps:
Instance:
Public class MyClass implements Runnable () {public void run () {// multithreading code} // other code}
MyClass m = new MyClass();Thread t = new Thread(m);t.start();
Functions of the start Method
Why can we implement multithreading in the above two ways?
The first method is easy to understand. Since the run method of the Thread class is rewritten, after the start method is called to start the Thread, jvm will call the run method rewritten by the subclass;
For the second method, after the start method is called to start the Thread, jvm will call the run method of the Thread class. The Code is as follows:
public void run() { if (target != null) { target.run(); }
}
Specifically, target is a member variable of the Thread class and its type is Runnable. When the Runnable object is used to construct a Thread, the target will reference this interface object. Therefore, when target. run () is executed, the run method of the interface object is actually executed.