(JAVA) Runnable realizes multithreading

1. Create a multi-threaded method

The first way to create multiple threads is to inherit Thread from the class and then override the run method. The second method is to implement the Runnable interface.
The execution steps of the second method are as follows:
1. Create an implementation class of Runnable interface;
2. Overwrite run method in the implementation class;
3. Create implementation class object of Runnable interface;
4. Create Thread class object, in the construction method Pass in the implementation class object of the Runnable interface;
5. Call the start method in the Thread class to start a new thread to execute the run method.

2. Code implementation

// 1.创建一个Runnable接口的实现类;
public class RunnableImpl implements Runnable {
    
    
//2.在实现类中重写run方法;
    @Override
    public void run() {
    
    
        for (int i = 0; i < 10; i++) {
    
    
            System.out.println(Thread.currentThread().getName()+"--->"+i);
        }
    }
}
//创建多线程的第二种方式
public class RunnableDemo {
    
    
    public static void main(String[] args) {
    
    
    // 3.创建Runnable接口的实现类对象;
        RunnableImpl r = new RunnableImpl();
    //创建Thread类对象,构造方法中传入Runnable接口的实现类对象;
        Thread t = new Thread(r);
    //调用Thread类中的start方法,开启新的线程执行run方法。
        t.start();
        for (int i = 0; i < 10; i++) {
    
    
           System.out.println(Thread.currentThread().getName()+"--->"+i);
        }
    }
}

Results of the

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45727931/article/details/108521080