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

[JAVA100例] 第60例:繼承 Thread 類創建線程入門

     編輯:Java 相關知識

本例展示最基礎的線程創建方式:定義類繼承 Thread,覆寫 run() 方法,主方法中實例化並調用 start() 啟動。

核心代碼

public class oneThread extends Thread {
  public oneThread() {}

  public void run() {
    System.out.println("...............oneThread begining................");
    int flag = 0;
    while (true) {
      if (flag == 20) {
        System.out.println("\n...............oneThread end............. ");
        break;
      }
      for (int i = 0; i < flag; i++) System.out.print("*");
      System.out.println("");
      flag++;
      try { sleep(100); } catch (Exception e) {}
    }
  }

  public static void main(String args[]) { new oneThread().start(); }
}

輸出效果

...............oneThread begining................
*
**
***
****
*****
******
*******
********
*********
**********
***********
************
*************
**************
***************
****************
*****************
******************
*******************
...............oneThread end............. 

關鍵知識點

  1. 繼承 Thread:最直觀但受單繼承限制
  2. run() 是執行體:業務邏輯寫在 run() 中
  3. start() 啟動新線程:JVM 分配棧空間、調用 run();直接調用 run() 不創建新線程
  4. sleep() 讓出 CPU:靜態方法 Thread.sleep(ms),拋出 InterruptedException
  5. 循環終止條件:flag 計數器控制迴圈次數

常見錯誤

  • new oneThread().run() ❌ — 同步執行,阻塞主線程
  • new oneThread().start() ✅ — 異步啟動新線程
  • 捕獲 InterruptedException 後不處理 ❌ — 應 Thread.currentThread().interrupt() 保留中斷狀態

現代替代:Lambda + Thread

new Thread(() -> {
  for (int i = 0; i < 20; i++) {
    System.out.println("*".repeat(i));
    try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; }
  }
}, "StarPrinter").start();

優勢:無需定義類、代碼內聚、支援捕獲局部變量。

生產環境建議

直接 new Thread() 僅適合學習/簡單工具。生產環境請使用:

  • ExecutorService 管理線程池
  • CompletableFuture 異步編排
  • ScheduledExecutorService 定時任務
  • JDK 21+ StructuredTaskScope 結構化併發
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved