本例展示最基礎的線程創建方式:定義類繼承 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.............
Thread.sleep(ms),拋出 InterruptedExceptionnew oneThread().run() ❌ — 同步執行,阻塞主線程new oneThread().start() ✅ — 異步啟動新線程InterruptedException 後不處理 ❌ — 應 Thread.currentThread().interrupt() 保留中斷狀態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 定時任務StructuredTaskScope 結構化併發