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博客