【线程】run()方法与start()方法有什么区别?

run()方法与start()方法有什么区别?
  通常,系统通过调用线程类的start()方法来启动一个线程、此时该线程处于就绪状态,等待调度,即就是这个线程可以被JVM来调度执行。在调度过程中,JVM底层通过调用线程类的run()方法来完成实际的操作,当run()方法结束后,此线程就会终止。

  如果直接调用线程类的run()方法,此时run()方法仅仅被当做一个普通的函数调用,程序中仍然只有主线程这一个线程

  start()方法能够异步的调用run()方法,但是直接调用run()方法却是同步的。

class MyThread implements Runnable{
    @Override
    public void run() {
        for(int i = 0;i < 10;i++){
            System.out.println(Thread.currentThread().getName()+i);
        }
    }

}
public class Test {
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
        new Thread(thread,"A").start();
        new Thread(thread,"B").start();
    }
}

在这里插入图片描述

class MyThread implements Runnable{
    @Override
    public void run() {
        for(int i = 0;i < 10;i++){
            System.out.println(Thread.currentThread().getName()+i);
        }
    }

}
public class Test {
    public static void main(String[] args) throws InterruptedException {
        MyThread thread = new MyThread();
       thread.run();
       thread.run();
    }
}

在这里插入图片描述
  通俗的来讲run()方法的怎么执行取决于调度者是谁、如果是JVM调度的run()方法,那么此时就是异步处理,如果是直接调用run()方法,那么就和普通函数没有什么区别。

猜你喜欢

转载自blog.csdn.net/zhao_miao/article/details/90633184