Thread implementation method two:
1. Customize a class to implement the runnable interface
class Thread implements Runnable
Looking at the source code, we can know that Thread implements the runnable interface
There is only one run abstract class in runnable
2. Implement the run method and define the tasks of the custom thread in the run method
3. Create a runnable implementation class object
4. Create a Thread method and pass the runnable implementation class object as an argument
Thread's constructor:
Thread(Runnable target) 分配新的
Thread
对象。
Thread(Runnable target ,String name) 分配新的
Thread
对象并这个可以给线程一个名字
5. And use the start method of the Thread method to open a thread thread
The start method is not static, to instantiate the object
Question 1: Is the implementation class of runnable a thread class?
No, only Thread and subclasses of Thread are thread objects
The implementation class of rannable is just an object that implements the rannable interface.
Question 2: Why can we call the start method of Thread to execute the run method of the implementation class of the runnable interface?
The source code is as follows:
Constructor of Thread class public Thread(Runnable target, String name) { init(null, target, name, 0); } The run method of the Thread class public void run() { if (target != null) { target.run(); } } The target member variable of the Thread class private Runnable target;
It turns out that when we call the start method of Thread, we call the run method of Thread,
And we pass an object of the runnable implementation class, and then the run method of the Thread will call the run method of the runnable implementation class
The following is an example code that implements the runnable interface:
public class Demo7 implements Runnable { @Override public void run() { for (int i = 0; i < 50; i++) { System.out.println(Thread.currentThread().getName()+i); } } public static void main(String[] args) { Demo7 demo = new Demo7(); Thread thread = new Thread(demo,"狗娃"); thread.run(); thread.start(); for (int i = 0; i < 50; i++) { System.out.println(Thread.currentThread().getName()+i); } } }