1. 簡介
- Runnable:接口,僅含
run() 方法。類實現該接口,再通過 new Thread(new MyRunnable()) 創建線程。
- Thread:類,實現了
Runnable。直接繼承 Thread 並重寫 run() 即可。
2. 異同點
| 維度 | Thread | Runnable |
| 類型 | 類 | 接口 |
| 繼承限制 | 單繼承,無法繼承其他類 | 可實現多接口,擴展性強 |
| 資源共享 | 每個線程獨有實例,資源不共享 | 多線程可共享同一 Runnable 實例,實現資源共享 |
| 推薦度 | 較低 | 推薦使用 |
3. 示例對比:賣票場景
Thread 方式:每線程各賣 10 張票(共 30 張)
class MyThread extends Thread {
private int ticket = 10;
public void run() {
for (int i = 0; i < 20; i++) {
if (this.ticket > 0) System.out.println(this.getName() + " 賣票:ticket" + this.ticket--);
}
}
}
public class ThreadTest {
public static void main(String[] args) {
new MyThread().start();
new MyThread().start();
new MyThread().start(); // 三個獨立實例,各賣 10 張
}
}
Runnable 方式:三線程共賣 10 張票(資源共享)
class MyThread implements Runnable {
private int ticket = 10;
public void run() {
for (int i = 0; i < 20; i++) {
if (this.ticket > 0) System.out.println(Thread.currentThread().getName() + " 賣票:ticket" + this.ticket--);
}
}
}
public class RunnableTest {
public static void main(String[] args) {
MyThread mt = new MyThread(); // 單一實例
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start(); // 三線程共享 mt,共賣 10 張
}
}
結果對比
- Thread:輸出顯示每線程獨立從 10 賣到 1,總計 30 張。
- Runnable:輸出顯示三線程交替賣票,總計 10 張,體現共享特性。