首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Thread start() 與 run() 關鍵差異詳解

     編輯:Java 相關知識

核心差異

方法作用是否啟動新線程可重複調用
start()啟動新線程,由 JVM 調度執行 run()是否(重複調用拋 IllegalThreadStateException)
run()普通實例方法,在當前線程同步執行否是

程式碼驗證

class MyThread extends Thread {
    @Override public void run() {
        System.out.println(Thread.currentThread().getName() + " is running");
    }
}

public class Demo {
    public static void main(String[] args) {
        Thread t = new MyThread();
        System.out.println(Thread.currentThread().getName() + " call run()");
        t.run();      // 輸出: main is running
        System.out.println(Thread.currentThread().getName() + " call start()");
        t.start();    // 輸出: Thread-0 is running
    }
}

執行結果

main call run()
main is running
main call start()
Thread-0 is running

證明:run() 在主線程執行;start() 建立新線程 Thread-0 執行。

源碼剖析 (JDK 1.7)

public synchronized void start() {
    if (threadStatus != 0) throw new IllegalThreadStateException();
    group.add(this);
    boolean started = false;
    try {
        start0(); // 本地方法,實際創建 OS 線程
        started = true;
    } finally { ... }
}

private native void start0(); // JVM 內部實現

public void run() {
    if (target != null) target.run(); // 若以 Runnable 建構,委派執行
}

常見錯誤與最佳實踐

  • 錯誤:直接呼叫 thread.run() 以為啟動了線程,實則同步阻塞主線程。
  • 正確:永遠使用 thread.start() 啟動線程。
  • 若需重複執行邏輯,請實作 Runnable 並多次 new Thread(runnable).start(),或使用執行緒池。

總結

start() = 啟動新線程(非同步);run() = 邏輯執行入口(同步)。切勿混淆。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved