建立執行緒最直覺的方式是繼承 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");
}
}
threadCount 確保每個實例擁有唯一 ID。start() 會完成平台相關初始化並排程執行緒;直接呼叫 run() 只是在當前執行緒同步執行,不具並發效果。setPriority() 調整優先權。start() 內部會向 JVM 註冊,因此即使主程式不保留參考,GC 也不會回收存活執行緒。synchronized 區塊呼叫 sleep(),其他執行緒仍無法進入該區塊。run() 返回後,堆疊框架銷毀,區域變數隨之消失。適合「本身即任務」的簡單場景。若需共享邏輯、實作多介面或使用執行緒池,建議改用 Runnable / Callable 搭配 ExecutorService,符合「組合優於繼承」原則。