start()方法会启动一个新的线程并执行,而run()方法只是类的一个普通方法,不会创建新的线程
代码演示
调用run()时:
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("current thread is : " + Thread.currentThread().getName());
}
});
thread.run();
}
控制台: (打印的当前线程仍为主线程)
current thread is : main
调用start()
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("current thread is : " + Thread.currentThread().getName());
}
});
thread.start();
}
控制台:(打印的当前线程为 新的子线程)
current thread is : Thread-0
源码追踪
start()方法
public synchronized void start() { if (threadStatus != 0) throw new IllegalThreadStateException(); group.add(this); boolean started = false; try { start0(); // 核心逻辑 started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } }
private native void start0();
start()内部调用的start0()为native方法,需要追踪JVM底层源码
https://hg.openjdk.java.net/jdk8u
Thread类在包java.lang下,故依次打开以下目录
browse - src / share / native / java / lang
https://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/f9ea6cf9425f/src/share/native/java/lang
start0方法,调用的是 JVM_StartThread、
进一步进入Hotspot源码 jdk8u/jdk8u/hotspot: e2ac513ec7b3 src/share/vm/prims/jvm.cpp
最终会创建一个新的线程并执行
run()方法
@Override
public void run() {
if (target != null) {
target.run();
}
}
@FunctionalInterface public interface Runnable { public abstract void run(); }
直接执行了 内部类run方法(Runnable的实现类),没有任何特殊操作;