------------------------------------------------------------------------------------------------------------
/** First way: Inherit the thread class
* 1. Define a class, and then let the class inherit the thread class
* 2. Overriding the Run method
* 3. Create an object of this class defined
* 4. Start thread
*/
Inherit the thread class
public class MyThread extends thread{
Public MyThread () {}
Public MyThread (String name) {
Super (name);
}
The Run method encapsulates the code that is to be executed by the thread, the code in the Run method, and the general depository is the more time-consuming code
public void Run () {
for (int i = 0; i <; i++) {
System.out.println (Thread.CurrentThread (). GetName () + "---" + i);
}
}
}
Test method
private static void Test () {
Creating objects
MyThread MT1 = new MyThread ();
MyThread mt2 = new MyThread ();
Start thread
public void Start () causes the thread to start executing, and the Java virtual machine calls the thread's Run method.
Mt1.start ();
Mt1.start ();//thread startup can only be one time
Mt2.start ();
}
------------------------------------------------------------------------------------------------------------
/** Second way: Implement Runnable interface
* (1): Create a class that implements the Runnable interface for this class
* (2): Rewrite the Run method
* (3): Create objects of this class
* (4): Creates an object of the thread class and then passes the object in 3 as a parameter to the thread
* (5): Start thread
*/
Implementing the Runnable Interface
public class MyThread2 implements Runnable {
Public MyThread2 () {
Super ();
}
public void Run () {
for (int x = 0; x < n × x + +) {
System.out.println (Thread.CurrentThread (). GetName () + "---" + x);
}
}
}
Test method
private static void Test2 () {
Create an Mythread object
MyThread2 MT = new MyThread2 ();
Creates an object of the thread class, and then passes the object in 3 as a parameter to the thread
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 thread
T1.start ();
T2.start ();
T3.start ();
}
------------------------------------------------------------------------------------------------------------
/** The Third way: using anonymous inner classes to implement
* New class Name/interface name () {
* Method rewrite;
* } ;
*/
Test method
Anonymous Inner class
private static void Test3 () {
New Thread () {
public void Run () {
SYSTEM.OUT.PRINTLN ("Thread executed ....") ");
}
}.start ();
}
------------------------------------------------------------------------------------------------------------
Three ways to implement multi-line Chengcheng in Java (inheritance, implementation, anonymous inner class)