

| 狀態 | 說明 | 觸發條件 |
|---|---|---|
| NEW | 新建 | new Thread() |
| RUNNABLE | 就緒/運行 | start()、獲得 CPU、yield()、鎖釋放 |
| BLOCKED | 阻塞 | sleep()、wait()、I/O、同步鎖等待 |
| TERMINATED | 死亡 | run() 結束、異常退出 |
阻塞三類型:等待阻塞、同步阻塞、其他阻塞(sleep/join/I/O)。
static int MAX_PRIORITY = 10; static int MIN_PRIORITY = 1; static int NORM_PRIORITY = 5; thread.setPriority(Thread.MAX_PRIORITY);
優先級只是提示,不保證執行順序,受平台影響大。
Thread.sleep(1000); // 釋放 CPU,保持鎖,到期進入 RUNNABLE
synchronized(obj) {
obj.wait(); // 釋放鎖,進入 WAITING
obj.notify(); // 喚醒一個
obj.notifyAll(); // 喚醒全部
}
必須在同步塊/方法中調用,否則拋 IllegalMonitorStateException。
Thread.yield(); // RUNNABLE → RUNNABLE,同優先級可能獲得 CPU
thread.join(); // 當前線程阻塞,等待 thread 結束
thread.setDaemon(true); // JVM 退出時不等待守護線程(如 GC)
class Actor extends Thread {
@Override public void run() { /* 任務邏輯 */ }
}
new Actor().start();
class Actress implements Runnable {
@Override public void run() { /* 任務邏輯 */ }
}
new Thread(new Actress()).start();
優勢:避免單繼承限制;任務與線程分離,利於線程池復用。
stop():強制殺死,數據不一致、鎖未釋放(已棄用)。interrupt() 單純調用:僅設置中斷標志,線程繼續跑。class Worker extends Thread {
volatile boolean running = true;
@Override public void run() {
while (running) { /* 業務邏輯 */ }
}
public void shutdown() { running = false; }
}
while (!Thread.currentThread().isInterrupted()) { /* ... */ }
// 外部調用 thread.interrupt() 設置標志,循環檢測退出
陷阱:若線程處於sleep()/wait(),調用interrupt()會清除中斷標志並拋InterruptedException,需捕獲後重新設置或拋出。
// 同步方法
public synchronized void add() { /* ... */ }
// 同步代碼塊(指定鎖對象)
public void add() {
synchronized (lockObj) { /* ... */ }
}
this 或 Class 對象)。Class 對象,非靜態鎖住實例,互不干擾。sleep() 不釋放鎖;wait() 釋放鎖。class Buffer {
List<Integer> list = new ArrayList<>();
int capacity = 10;
public synchronized void produce(int v) throws InterruptedException {
while (list.size() == capacity) wait();
list.add(v);
notifyAll();
}
public synchronized int consume() throws InterruptedException {
while (list.isEmpty()) wait();
int v = list.remove(0);
notifyAll();
return v;
}
}

notify() 隨機移動一個線程從 WaitSet → EntrySet;notifyAll() 全部移動。ReentrantLock、ReadWriteLock、Condition.await/signal。AtomicInteger、CAS、ABA 問題。ExecutorService、ThreadPoolExecutor、拒絕策略。ConcurrentHashMap、BlockingQueue、CopyOnWriteArrayList。CountDownLatch、CyclicBarrier、Semaphore、Phaser。