Multithreading (1) Runnable interface

Implement Runnable

  • Define the MyRunnable class to implement the Runnable interface
  • Implement the run() method and write the thread execution body
  • Create a thread object and call the start() method to start the thread
    It is recommended to use Runnable objects because of the limitations of java single inheritance
package study;

//实现Runnable接口,重写run方法,执行线程丢入runnable接口实现类,调用start
public class TestThread implements Runnable {
    
    


    @Override
    public void run() {
    
    
        for (int i = 0; i < 200; i++) {
    
    
            System.out.println("我在看代码---"+i);
        }
    }

    public static void main(String[] args) {
    
    
        //创建runnable接口的实现类对象
        TestThread testThread = new TestThread();
        //创建线程对象,代理
        Thread thread = new Thread(testThread);
        thread.start();
        for (int i = 0; i < 1000; i++) {
    
    
            System.out.println("我在学习多线程---"+i);
        }
    }
}

insert image description here
It can be seen that the simultaneous
advantage
It is convenient for the same object to be used by multiple threads

new Thread(thread,name).start();

Guess you like

Origin blog.csdn.net/sand_wich/article/details/107633710