Java 提供兩種建立執行緒的方式:繼承 Thread 類別或實作 Runnable 介面。本範例示範繼承 Thread 並覆寫 run() 方法的基本模式。
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); // 休眠 0.1 秒(靜態方法 Thread.sleep)
} catch (Exception e) {}
}
}
// 主程式:啟動執行緒
public static void main(String args[]) {
new oneThread().start(); // 呼叫 start() 而非 run()!
}
}
| 關鍵點 | 說明 |
|---|---|
extends Thread | 繼承 Thread 類別,本身即為一個執行緒物件 |
覆寫 run() | 定義執行緒執行邏輯,JVM 呼叫此方法 |
呼叫 start() | 啟動執行緒,JVM 會排程稍後呼叫 run();直接呼叫 run() 只是普通方法呼叫,不會開啟新執行緒 |
sleep(100) | 靜態方法,讓「目前執行緒」休眠指定毫秒數,需處理 InterruptedException |
| 迴圈終止條件 | 使用旗標變數控制迴圈結束,避免無限迴圈 |
...............oneThread begining................ * ** *** **** ***** ...... ******************** ...............oneThread end.............
this 即為執行緒物件,可呼叫 getName()、setPriority() 等方法// 方式二預覽
public class MyTask implements Runnable {
public void run() { /* 執行邏輯 */ }
}
// 使用時:new Thread(new MyTask()).start();
繼承 Thread 適合簡單、獨立的執行緒任務;實作 Runnable 則更符合「關注點分離」原則,也是後續執行緒池、Callable/Future 等進階機制的基礎。