一、start()和run()的比較
start()方法纔是啓動線程的正確姿勢!
/**
* 啓動線程的方式:run()和start()
*/
public class StartThreadTest {
public static void main(String[] args) {
StartRunnable runnable = new StartRunnable();
// 使用run()方法啓動
runnable.run();
// 使用start()方法啓動
new Thread(runnable).start();
}
}
class StartRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
發現使用run()方法啓動時主線程執行的,使用start()方法纔是啓動子線程執行。
二、start()方法
1. 概述
- 啓動新線程:
即主線程執行thread.start()方法後,主線程通知JVM,在有空閒的情況下,啓動、運行這個新線程。具體什麼時間運行,需要由線程調度器決定。 - 準備工作:
在通知JVM來執行新線程前,需要做一些準備工作:使新線程的狀態處於就緒狀態,指的是新線程已經獲取到了除了CPU以外的其他資源(上下文、棧、寄存器等)。 - 線程執行:
當JVM來執行這個線程時,即獲取到了CPU,去執行run()方法中的代碼。 - 不能重複start():
重複start()會拋出異常,具體實現見下面源碼
2. Thread的start()方法源碼
- 檢查新線程的狀態
初始狀態爲0 - 加入線程組
- 執行start0()方法
start0()是一個native方法,即用C、C++編寫的方法。
三、run()方法
1. 概述
- run()方法就是一個簡單的普通的方法,所以調用會直接主線程執行run()中的內容。