Thread中的start和run方法的区别(JVM角度)

当调用start()方法的时候,JVM会创建一个新的线程,而run方法会沿用主线程所在的线程.



JDK文档中是这样描述的

  • start
    public void start()

导致此线程开始执行; Java虚拟机调用此线程的run方法。
结果是两个线程同时运行:当前线程(从调用返回到start方法)和另一个线程(执行其run方法)。
不止一次启动线程是不合法的。 特别地,一旦线程完成执行就可能不会重新启动。
*异常 *:IllegalThreadStateException - 如果线程已经启动。

  • run
    public void run()
    如果这个线程是使用单独的Runnable运行对象构造的,则Runnable对象的run方法; 否则,此方法不执行任何操作并返回。
    Thread的Thread应该覆盖此方法。

start()方法源码

start()方法源码

其中最关键的就是Native方法start0()

start0()方法源码网址

这里给个小提示,进入源码列表是http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file
start0()方法引自于jvm.h中的JVM_StartThread()方法
JVM_StartThread()源码网址http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/7576bbd5a03c/src/share/vm/prims/jvm.cpp
部分源码,选中的蓝色部分是核心代码

选中代码就是去创建一个新的线程

代码效果演示:

  • 自定义MyThread类
public class MyThread extends Thread {

    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread start : "+ this.name + " i = "+i);
        }
    }
}
  • 创建测试类ThreadDemo
    • 1.调用start()方法
public class ThreadDemo {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread("Thread1");
        MyThread thread2 = new MyThread("Thread2");
        MyThread thread3 = new MyThread("Thread3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

运行结果

Thread start : Thread1 i = 0
Thread start : Thread2 i = 0
Thread start : Thread1 i = 1
Thread start : Thread2 i = 1
Thread start : Thread1 i = 2
Thread start : Thread2 i = 2
Thread start : Thread1 i = 3
Thread start : Thread2 i = 3
Thread start : Thread1 i = 4
Thread start : Thread2 i = 4
Thread start : Thread3 i = 0
Thread start : Thread3 i = 1
Thread start : Thread3 i = 2
Thread start : Thread3 i = 3
Thread start : Thread3 i = 4


  • 2.调用run方法
public class ThreadDemo {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread("Thread1");
        MyThread thread2 = new MyThread("Thread2");
        MyThread thread3 = new MyThread("Thread3");
        thread1.run();
        thread2.run();
        thread3.run();
    }
}

运行结果

Thread start : Thread1 i = 0
Thread start : Thread1 i = 1
Thread start : Thread1 i = 2
Thread start : Thread1 i = 3
Thread start : Thread1 i = 4
Thread start : Thread2 i = 0
Thread start : Thread2 i = 1
Thread start : Thread2 i = 2
Thread start : Thread2 i = 3
Thread start : Thread2 i = 4
Thread start : Thread3 i = 0
Thread start : Thread3 i = 1
Thread start : Thread3 i = 2
Thread start : Thread3 i = 3
Thread start : Thread3 i = 4

你可能感兴趣的:(Thread中的start和run方法的区别(JVM角度))