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

Java 線程啟動:start() 與 run() 的關鍵差異深度解析

     編輯:Java 程式設計入門

在 Java 多線程開發中,啟動線程的標準方式是呼叫 start() 方法。但許多開發者會好奇:直接呼叫 run() 方法能否達成相同效果?答案是否定的,兩者有本質區別。本文透過程式碼實驗深入剖析這一核心概念。

直接呼叫 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() 根本未啟動新線程,只是單線程循序執行。

正確啟動:呼叫 start() 方法

將 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(),主線程繼續向下執行,實現真正的多線程併發。

核心結論

  • start():請求 JVM 建立新線程,由 JVM 調度執行 run(),實現多線程併發。
  • run():單純的方法呼叫,在當前線程執行,無法實現併發,屬於同步阻塞操作。

記住:只有透過 start() 將線程交給 JVM 管理,才能發揮多線程優勢。

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