
| 方式 | 優點 | 缺點 |
|---|---|---|
繼承 Thread 類 | 簡單直接 | 單繼承限制,若已繼承 Applet 等則無法使用 |
實現 Runnable 接口 | 支持多實現、邏輯與控制分離、可共享同一實例 | 需額外 new Thread(runnable) |
public class TestThread2 implements Runnable {
private int threadId;
public TestThread2(int id) { this.threadId = id; }
public static void main(String[] args) {
Thread t1 = new Thread(new TestThread2(1));
Thread t2 = new Thread(new TestThread2(2));
t1.setPriority(Thread.MIN_PRIORITY); // 1
t2.setPriority(Thread.MAX_PRIORITY); // 10
t1.start(); t2.start();
}
@Override public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(threadId + ":" + i);
}
}
}
注意:優先級只影響調度概率,不保證執行順序。
new Thread(),調用 start() 進入就緒run();時間片用完回就緒sleep()、I/O 等待、鎖等待;條件消除後回就緒run() 正常結束或異常終止(不推薦 stop()/destroy())
synchronized 方法:鎖住 thissynchronized(obj) 塊:鎖住指定對象四個必要條件:互斥、請求與保持、不剝佔、循環等待。恢復策略:
Timer:單線程調度器,類似鬧鐘TimerTask:實現 Runnable 的抽象類,業務邏輯寫在 run()Timer 可調度多個 TimerTask,但任務間會阻塞;需並行時建議多 Timer 實例只有當程序「天然要求多個代碼塊並發執行且順序不確定」時,多線程才是合適的。若只是為了簡化邏輯或順序執行,用循環更高效。