public class MyThread extends Thread {
@Override
public void run() {
System.out.println("MyThread......");
}
public static void main(String[] args) {
new MyThread().start();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("MyRunnable......");
}
public static void main(String[] args) {
new Thread(new MyRunnable()).start();
}
}
| 維度 | 繼承 Thread | 實現 Runnable |
|---|---|---|
| 繼承限制 | 單繼承,無法繼承其他類 | 可實現多接口,靈活 |
| 數據共享 | 每個線程獨立數據副本 | 同一 Runnable 實例可共享數據 |
| 耦合度 | 線程邏輯與線程控制耦合 | 任務邏輯與線程控制分離 |
| 線程池適配 | 不直接支持 | 完美適配 ExecutorService |
start():啟動新線程,JVM 底層調用 native start0()(JNI 技術)。run():單線程順序執行,無並發效果。
class TicketSeller implements Runnable {
private int tickets = 10;
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (tickets > 0) System.out.println("賣票:" + tickets--);
}
}
}
public static void main(String[] args) {
TicketSeller seller = new TicketSeller();
new Thread(seller).start();
new Thread(seller).start();
new Thread(seller).start(); // 總共賣 10 張,實現共享
}
Thread 本身實現了 Runnable,兩者統一於 Runnable 抽象任務接口。