實作 Runnable 介面將「任務邏輯」與「執行緒控制」分離,符合組合優於繼承原則,也是執行緒池、Callable、Future 等進階 API 的基礎模式。
public class twothread implements Runnable {
// 建構子:建立並啟動第二條執行緒
twothread() {
// 取得主執行緒
Thread t1 = Thread.currentThread();
t1.setName("The first main thread");
System.out.println("The running thread: " + t1);
// 以「this(Runnable 實例)」+ 名稱建立新執行緒
Thread t2 = new Thread(this, "the second thread");
System.out.println("creat another thread");
t2.start(); // 啟動 t2
try {
System.out.println("first thread will sleep");
Thread.sleep(3000); // 主執行緒休眠 3 秒
} catch (InterruptedException e) {
System.out.println("first thread has wrong");
}
System.out.println("first thread exit");
}
// 實作 Runnable 唯一抽象方法
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("Sleep time for thread 2: " + i);
Thread.sleep(1000); // 子執行緒每秒列印一次
}
} catch (InterruptedException e) {
System.out.println("thread has wrong");
}
System.out.println("second thread exit");
}
public static void main(String args[]) {
new twothread(); // 建構子內已啟動執行緒
}
}
The running thread: Thread[The first main thread,5,main] creat another thread first thread will sleep Sleep time for thread 2: 0 Sleep time for thread 2: 1 Sleep time for thread 2: 2 Sleep time for thread 2: 3 Sleep time for thread 2: 4 second thread exit first thread exit
| 概念 | 繼承 Thread | 實作 Runnable |
|---|---|---|
| 關係 | 是一個執行緒 | 是一個任務 |
| 繼承限制 | 受單繼承限制 | 可自由繼承其他類別 |
| 共享資料 | 需額外處理 | 天然適合多執行緒共享同一任務實例 |
| 執行緒池相容 | 不直接支援 | 完美支援 ExecutorService |
| 取得執行緒資訊 | this.getName() | Thread.currentThread().getName() |
public class SharedTask implements Runnable {
private int counter = 0;
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + " counter=" + counter++);
}
}
public static void main(String[] args) {
SharedTask task = new SharedTask(); // 單一任務實例
new Thread(task, "Thread-A").start();
new Thread(task, "Thread-B").start();
new Thread(task, "Thread-C").start();
}
}
輸出會顯示三條執行緒共同操作同一 counter,驗證共享資料特性(亦暴露執行緒安全問題,需同步機制解決)。
executor.submit(new MyTask()) 替代手動 new Thread()Callable<V> 配合 Future<V> 取得非同步結果new Thread(() -> { /* 邏輯 */ }).start()實作 Runnable 是 Java 並發程式設計的基石,掌握其精髓才能駕馭更高階的並發框架。