Thread.start() & run()
public static void main(String[] args) { new Thread(new Runnable() {@Overridepublic void run() {System.out.println("2432");}}).start();
}public class Thread implements Runnable {//通过构造方法调用init方法,在init方法中赋值private Runnable target;//target赋值过程public Thread(Runnable target) {init(null, target, "Thread-" + nextThreadNum(), 0);}private void init(ThreadGroup g, Runnable target, String name,long stackSize) {init(g, target, name, stackSize, null, true);}private void init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc,boolean inheritThreadLocals) {...this.target = target;...}//调用Runnable接口实现类中的run()@Overridepublic void run() {if (target != null) {target.run();}}/** start()方法中并没有调用run(),run()为什么能执行呢?* 当前代码是在main线程中执行,如果直接调用run()那就不是新启线程了。** 当调用Thread对象的start方法后,它的内部调用start0方法。* 接着通过JNI技术调用虚拟机里用C++编写的方法,在该方法中会创建JavaThread对象。* 在其构造方法中调用系统函数pthread_create创建内核线程。* 最终在内核线程中执行Thread对象的run方法。*/public synchronized void start() {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 thenit will be passed up the call stack */}}}//最终通过hotspot调用C++通过系统函数创建线程private native void start0();}
hotspot结论参考:
Thread类的start()方法创建线程的底层分析_thread.start()-CSDN博客