在 Java 多線程開發中,啟動線程的標準方式是呼叫 start() 方法。但許多開發者會好奇:直接呼叫 run() 方法能否達成相同效果?答案是否定的,兩者有本質區別。本文透過程式碼實驗深入剖析這一核心概念。
先看一個簡單範例,直接呼叫 run() 方法:
public class Test {
public static void main(String[] args) {
TestThread tt = new TestThread();
tt.run(); // 直接呼叫 run()
}
}
class TestThread extends Thread {
static int i = 0;
final static int MAX_I = 10;
@Override
public void run() {
while (i < MAX_I) {
System.out.println(i++);
}
}
}
執行結果輸出 0 到 9,乍看之下似乎正常運作。但若在主線程中新增輸出語句:
public static void main(String[] args) {
TestThread tt = new TestThread();
tt.run();
System.out.println("Printed by main thread");
}
結果顯示 "Printed by main thread" 出現在最後,說明 run() 方法阻塞了主線程,這只是普通的方法呼叫,並未建立新線程。
在主線程與 run() 方法中分別列印線程名稱:
public static void main(String[] args) {
TestThread tt = new TestThread();
tt.run();
System.out.println(Thread.currentThread().getName()); // main
System.out.println("Printed by main thread");
}
// TestThread.run() 中新增:
System.out.println(Thread.currentThread().getName()); // 同樣輸出 main
輸出結果證實:兩處皆為 "main" 線程,直接呼叫 run() 根本未啟動新線程,只是單線程循序執行。
將 tt.run() 改為 tt.start():
public static void main(String[] args) {
TestThread tt = new TestThread();
tt.start(); // 啟動新線程
System.out.println(Thread.currentThread().getName()); // main
System.out.println("Printed by main thread");
}
執行結果顯示 "main"、"Thread-0" 交替出現,證明已建立獨立線程並發執行。JVM 分配新線程執行 run(),主線程繼續向下執行,實現真正的多線程併發。
run(),實現多線程併發。記住:只有透過 start() 將線程交給 JVM 管理,才能發揮多線程優勢。