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

2019-08-13  本文已影响0人  叫我胖虎大人

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



JDK文档中是这样描述的

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

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
部分源码,选中的蓝色部分是核心代码

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

代码效果演示:

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);
        }
    }
}
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


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

上一篇下一篇

猜你喜欢

热点阅读