线程的start方法和run方法的区别

run方法及结果

public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("current thread name is:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.run();
        System.out.println("current thread name is:" + Thread.currentThread().getName());
    }
}
current thread name is:main
current thread name is:main

start方法及结果

public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("current thread name is:" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        System.out.println("current thread name is:" + Thread.currentThread().getName());
    }
}
current thread name is:Thread-0
current thread name is:main

结论

源码解释:Thread的start方法会调用jvm的StartTread方法去创建一个子线程,并通过子线程去调用run方法。

  • 调用start方法会创建一个新的子进程并启动
  • run方法是指Thread的一个普通方法的调用

猜你喜欢

转载自www.cnblogs.com/bobi1234/p/10745588.html