In Java, You can implement multithreading in two ways. One is to inherit the Thread class and the other is to implement the runnable interface;
The thread class is defined in the Java. lang package. A class inherits the Thread class and overwrites
The run () method can implement multi-threaded operations, but a class can only inherit one parent class, which is a limitation of this method,
The following is an example:
Package org. thread. Demo;
Class mythread extends thread {
Private string name;
Public mythread (string name ){
Super ();
This. Name = Name;
}
Public void run (){
For (INT I = 0; I <10; I ++ ){
System. Out. println ("thread start:" + this. Name + ", I =" + I );
}
}
}
Package org. thread. Demo;
Public class threaddemo01 {
Public static void main (string [] ARGs ){
Mythread MT1 = new mythread ("thread ");
Mythread MT2 = new mythread ("thread B ");
Mt1.run ();
Mt2.run ();
}
}
However, the results are regular at this time. The first object is executed first, and then the second object is executed without running each other. In the JDK documentation, we can find that once the START () method is called, The run () method is found through JVM. Start
Start () method start thread:
Package org. thread. Demo;
Public class threaddemo01 {
Public static void main (string [] ARGs ){
Mythread MT1 = new mythread ("thread ");
Mythread MT2 = new mythread ("thread B ");
Mt1.start ();
Mt2.start ();
}
}; In this way, the program can normally complete interactive operation. So why do we have to use the START (); Method to start multithreading?
In the installation environment of JDK, src.zip is the full Java source program. By finding the definition of the START () method in thread, we can find that private native void start0 () is used in this method (); the native keyword indicates that the underlying functions of the operating system can be called, so this technology becomes JNI technology (Java Native Interface)
· Runnable interface
In actual development, a multi-threaded operation rarely uses the Thread class, but is completed through the runnable interface.
Public interface runnable {
Public void run ();
}
Example:
Package org. runnable. Demo;
Class mythread implements runnable {
Private string name;
Public mythread (string name ){
This. Name = Name;
}
Public void run (){
For (INT I = 0; I <100; I ++ ){
System. Out. println ("thread start:" + this. Name + ", I =" + I );
}
}
};
Reference from: http://java.chinaitlab.com/line/820728.html