Java implements multithreading in three ways (inheritance, implementation, anonymous internal class), java Multithreading
Bytes ------------------------------------------------------------------------------------------------------------
/**Method 1: Inherit the Thread class
* 1. Define a class and then let the class inherit the Thread class
* 2. Override the run method.
* 3. Create a defined object for this class
* 4. Start the thread
*/
// Inherit the Thread class
Public class MyThread extends Thread {
Public MyThread (){}
Public MyThread (String name ){
Super (name );
}
// The Code encapsulated in the run method should be the code to be executed by the thread. The Code principles in the run method are generally time-consuming code.
Public void run (){
For (int I = 0; I <200; I ++ ){
System. out. println (Thread. currentThread (). getName () + "---" + I );
}
}
}
// Test Method
Private static void Test (){
// Create an object
MyThread mt1 = new MyThread ();
MyThread mt2 = new MyThread ();
// Start the thread
// Public void start () enables the thread to start execution; Java Virtual Machine calls the run method of the thread.
Mt1.start ();
// Mt1.start (); // The thread can be started only once.
Mt2.start ();
}
Bytes ------------------------------------------------------------------------------------------------------------
/**Method 2: implement the Runnable interface
* (1): Create a class to implement the Runnable interface.
* (2): override the run method.
* (3): Create an object of this class
* (4): Create a Thread Class Object and pass the object in 3 as a parameter to the Thread
* (5): Start the thread.
*/
// Implement the Runnable interface
Public class MyThread2 implements Runnable {
Public MyThread2 (){
Super ();
}
Public void run (){
For (int x = 0; x <200; x ++ ){
System. out. println (Thread. currentThread (). getName () + "---" + x );
}
}
}
// Test Method
Private static void Test2 (){
// Create a MyThread object
MyThread2 mt = new MyThread2 ();
// Create a Thread Class Object and pass the object in 3 to the Thread as a parameter
// Public Thread (Runnable target)
Thread t1 = new Thread (mt, "Zhang Fei ");
Thread t2 = new Thread (mt, "Guan Yu ");
Thread t3 = new Thread (mt, "Liu Bei ");
// Start the thread
T1.start ();
T2.start ();
T3.start ();
}
Bytes ------------------------------------------------------------------------------------------------------------
/**Method 3: Use an anonymous internal class
* New Class Name/Interface Name (){
* Method rewriting;
*};
*/
// Test Method
// Anonymous internal class
Private static void Test3 (){
New Thread (){
Public void run (){
System. out. println ("thread executed ....... ");
}
}. Start ();
}
Bytes ------------------------------------------------------------------------------------------------------------