Thread 類別: 覆寫 run() 方法Runnable 介面: 實作 run(),再傳入 Thread 建構子import java.io.*;
public class MultiThread {
public static void main(String args[]) {
System.out.println("我是主執行緒!");
// 方式1:繼承 Thread
ThreadUseExtends thread1 = new ThreadUseExtends();
// 方式2:實作 Runnable
Thread thread2 = new Thread(new ThreadUseRunnable(), "SecondThread");
thread1.start(); // 啟動進入就緒狀態
// thread1.setPriority(6); // 優先級 1-10,預設 5
System.out.println("主執行緒將掛起 7 秒!");
try { Thread.sleep(7000); } catch (InterruptedException e) { return; }
System.out.println("又回到了主執行緒!");
if (thread1.isAlive()) {
thread1.stop(); // 注意:stop() 已棄用,教學示範用
System.out.println("thread1 休眠過長, 主執行緒殺掉了 thread1!");
} else {
System.out.println("主執行緒沒發現 thread1, 已順序結束!");
}
thread2.start();
System.out.println("主執行緒又將掛起 7 秒!");
try { Thread.sleep(7000); } catch (InterruptedException e) { return; }
System.out.println("又回到了主執行緒!");
if (thread2.isAlive()) {
thread2.stop();
System.out.println("thread2 休眠過長,主執行緒殺掉了 thread2!");
} else {
System.out.println("主執行緒沒發現 thread2, 已順序結束!");
}
System.out.println("程式結束,按任意鍵繼續!");
try { System.in.read(); } catch (IOException e) { System.out.println(e); }
}
}
// 繼承 Thread 類別
class ThreadUseExtends extends Thread {
public ThreadUseExtends() {}
public void run() {
System.out.println("我是 Thread 子類的執行緒實例!");
System.out.println("我將掛起 10 秒!");
System.out.println("回到主執行緒, 請稍等...");
try { sleep(10000); } catch (InterruptedException e) { return; }
// run() 結束,執行緒自動終止
}
}
// 實作 Runnable 介面
class ThreadUseRunnable implements Runnable {
public ThreadUseRunnable() {}
public void run() {
System.out.println("我是 Thread 類的執行緒實例並以實作 Runnable 介面的類為參數!");
System.out.println("我將掛起 1 秒!");
System.out.println("回到主執行緒, 請稍等...");
try { Thread.sleep(1000); } catch (InterruptedException e) { return; }
}
}
| 概念 | 說明 |
|---|---|
start() vs run() | start() 啟動新執行緒(呼叫 run());直接呼叫 run() 只是普通方法呼叫,不會新開執行緒 |
| 執行緒狀態 | 新建 → 就緒 → 執行 → 阻塞/等待 → 終止 |
| 優先級 | 1(MIN) ~ 10(MAX),預設 5(NORM);新執行緒繼承父執行緒優先級 |
sleep() | 靜態方法,讓當前執行緒暫停指定毫秒,不釋放鎖 |
stop() 棄用 | 強制終止會導致鎖未釋放、資料不一致;正確做法:interrupt() + 旗標檢查 |
isAlive() | 執行緒已啟動且未終止返回 true |
ExecutorService + Runnable/Callable 管理執行緒池executor.shutdown() + awaitTermination()Thread.currentThread().isInterrupted() 檢查Thread 實例,改用高階併發工具(Future、CompletableFuture、CountDownLatch 等)修改程式碼觀察行為差異:調整 sleep() 時間、設定 setPriority()、交換啟動順序、加入 join() 等待終止。