1. Inherit Thread and override the run() method
(1) Inherit the Thread class and override the run() method. (2) Create a subclass object. (3) Call the start() method of the Thread object to start the Thread
public class Demo extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(getName() + ":" + "i=" + i); } } public static void main(String[] args) { Demo d = new Demo(); D.s etName (" thread 1 "); d.start(); }}Copy the code
GetName () : Can get the name of the current thread. SetName () : Sets the thread name.
2. Implement the Runable interface
(1) Implement the run() method in the interface, encapsulate the task code of the thread into the run method; (2) Create Thread objects from the Thread class and pass the Runnable interface subclass object as a parameter to the Thread constructor; (3) Call the start() method of the thread object to start the thread
public class Demo implements Runnable { public void run() { for (int i = 0; i < 10; i++) { System.out.println("i=" + i); } } public static void main(String[] args) { Demo d = new Demo(); Thread tr = new Thread(d); Tr.start (); // Pass the Runnable subclass object as an argument to the Thread constructor. }}Copy the code
3. Implement the benefits of the Runnable interface for creating threads
- The task of the thread is separated from the subclass of the thread and encapsulated separately. According to the idea of object orientation, the task is encapsulated as object.
- Avoiding the limitations of Java single inheritance;
So this is a common way