必須調用
Thread.start()啟動線程,這會創建新調用棧並異步執行run()。直接調用run()只是普通方法調用,仍在主線程中同步執行。
Thread thread = new Thread(() -> {
System.out.println("子線程運行:" + Thread.currentThread().getName());
});
thread.start(); // 正確啟動
// thread.run(); // 錯誤:主線程同步執行

Future/ExecutorService 使用
TIMED_WAITINGinterrupt() 喚醒拋出 InterruptedExceptionwait() 釋放鎖,進入 WAITING,加入對象等待隊列notify() 喚醒單個,notifyAll() 喚醒全部,重新競爭鎖park() 消費許可證(無則阻塞),unpark() 發放許可證Thread.interrupted()Lock.newCondition() 創建,綁定特定 LockawaitNanos、awaitUntil、awaitUninterruptiblyrun() 方法正常返回Thread.stop():已棄用,釋放所有鎖導致數據不一致Thread.destroy():未實現,不可用public class GracefulShutdownTask implements Runnable {
private volatile boolean running = true;
public void shutdown() { running = false; }
@Override
public void run() {
while (running && !Thread.currentThread().isInterrupted()) {
try {
// 業務邏輯
doWork();
// 可中斷阻塞點
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 重置中斷狀態
break; // 退出循環
}
}
cleanup(); // 資源釋放
}
}
Thread daemon = new Thread(() -> {
while (true) { /* 後台任務 */ }
});
daemon.setDaemon(true); // 必須在 start() 前設置
daemon.start();
Thread t = new Thread(() -> { /* 耗時任務 */ });
t.start();
t.join(); // 主線程阻塞,直到 t 結束
t.join(5000); // 最多等待 5 秒
原理:join() 內部調用 this.wait(0),線程結束時 JVM 自動 this.notifyAll()。
Thread thread = new Thread(() -> {
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println("子線程結束");
});
thread.start();
synchronized (thread) {
thread.wait(); // 等待 thread 對象鎖被 notifyAll(線程結束時自動觸發)
}
System.out.println("主線程結束");
Thread[] threads = new Thread[5];
for (int i = 0; i < 5; i++) {
final int num = i + 1;
threads[i] = new Thread(() -> {
synchronized (lock) {
try { lock.wait(); } catch (InterruptedException e) { /* 被喚醒 */ }
// 此處仍持有鎖,需退出同步塊才真正釋放
}
});
threads[i].start();
}
// 2秒後中斷所有
Thread.sleep(2000);
for (Thread t : threads) t.interrupt();
for (Thread t : threads) t.join();
輸出驗證:中斷喚醒 → 執行同步塊後續代碼 → 退出同步塊 → 線程結束。
並行:多核 CPU 同一時刻執行多線程。並發:單核 CPU 時間片輪轉交替執行多線程,宏觀並行、微觀串行。Java 線程調度依賴操作系統,現代多核環境下並存並發與並行。
ExecutorService 管理生命週期、復用線程、控制併發度Runnable/Callablevolatile boolean 標誌 + interrupt() + 可中斷阻塞點處理CountDownLatch、CyclicBarrier、Semaphore、CompletableFuture、BlockingQueue掌握線程啟動、暫停、結束、監聽的底層機制與高級 API,是編寫高併發、高可靠 Java 系統的核心功力。