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

Java 線程入門:繼承 Thread 類別實作簡易多線程範例

     編輯:Java 相關知識

建立執行緒最直覺的方式是繼承 java.lang.Thread 並覆寫 run() 方法。本文以 SimpleThread 為例,示範如何啟動多條執行緒並觀察其並發行為。

核心程式碼解析

public class SimpleThread extends Thread {
    private int countDown = 5;
    private int threadNumber;
    private static int threadCount = 0;

    public SimpleThread() {
        threadNumber = ++threadCount;
        System.out.println("Making " + threadNumber);
    }

    public void run() {
        while (true) {
            System.out.println("Thread " + threadNumber + "(" + countDown + ")");
            if (--countDown == 0) return; // 計數歸零,執行緒結束
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) new SimpleThread().start();
        System.out.println("All Threads Started");
    }
}

關鍵點逐項拆解

  1. 建構子只負責編號:靜態變數 threadCount 確保每個實例擁有唯一 ID。
  2. run() 是執行緒本體:JVM 會在獨立呼叫堆疊上執行此方法;回傳即代表執行緒結束。
  3. 必須呼叫 start() 而非 run():start() 會完成平台相關初始化並排程執行緒;直接呼叫 run() 只是在當前執行緒同步執行,不具並發效果。
  4. 輸出順序不可預測:作業系統排程器決定時間片分配,除非呼叫 setPriority() 調整優先權。
  5. 執行緒自註冊機制:start() 內部會向 JVM 註冊,因此即使主程式不保留參考,GC 也不會回收存活執行緒。

常見迷思釐清

  • sleep() 不會釋放鎖:若在 synchronized 區塊呼叫 sleep(),其他執行緒仍無法進入該區塊。
  • 執行緒結束即釋放所有資源:run() 返回後,堆疊框架銷毀,區域變數隨之消失。

何時選擇繼承 Thread?

適合「本身即任務」的簡單場景。若需共享邏輯、實作多介面或使用執行緒池,建議改用 Runnable / Callable 搭配 ExecutorService,符合「組合優於繼承」原則。

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