Java 透過 Thread 類別與 Runnable 介面提供多執行緒支援。執行緒是 Thread 或其子類別的實例,核心在於 run() 方法定義任務邏輯。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running...");
}
}
// 使用
Thread t1 = new MyThread();
t1.start(); // 啟動執行緒
class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Runnable task running...");
}
}
// 使用
Thread t2 = new Thread(new MyTask());
t2.start();
start():向 JVM 註冊執行緒,排程執行 run(),**非同步返回**。NORM_PRIORITY)。setPriority(int) / getPriority()。Thread t1 = new MyThread();
Thread t2 = new Thread(new MyTask());
t1.setPriority(Thread.MAX_PRIORITY); // 10
t2.setPriority(Thread.MIN_PRIORITY); // 1
t1.start(); t2.start();
執行緒 A 讀取資料,執行緒 B 同時修改 → 髒讀、更新遺失、不一致。
class DataStore {
private int value = 0;
// 同步方法:鎖定 this
public synchronized void write(int v) {
value = v;
}
public synchronized int read() {
return value;
}
}
生產者-消費者經典模型:
class Warehouse {
private int stock = 0;
private final int CAPACITY = 10;
public synchronized void produce() throws InterruptedException {
while (stock >= CAPACITY) wait(); // 滿了等待
stock++;
notifyAll(); // 通知消費者
}
public synchronized void consume() throws InterruptedException {
while (stock == 0) wait(); // 空了等待
stock--;
notifyAll(); // 通知生產者
}
}
wait():釋放鎖,進入 WAITING,需在 synchronized 區塊呼叫。notify():喚醒一個等待執行緒;notifyAll():喚醒全部。while 而非 if(防虛假喚醒)。class Producer extends Thread {
private Warehouse warehouse;
public Producer(Warehouse w) { warehouse = w; }
public void run() {
try { while (true) { warehouse.produce(); Thread.sleep(100); } }
catch (InterruptedException ignored) {}
}
}
class Consumer extends Thread {
private Warehouse warehouse;
public Consumer(Warehouse w) { warehouse = w; }
public void run() {
try { while (true) { warehouse.consume(); Thread.sleep(150); } }
catch (InterruptedException ignored) {}
}
}
public class Main {
public static void main(String[] args) {
Warehouse w = new Warehouse();
new Producer(w).start();
new Consumer(w).start();
}
}
| 工具 | 替代目標 |
|---|---|
ReentrantLock | synchronized(更多功能) |
Condition | wait/notify |
BlockingQueue | 生產者消費者手動實作 |
Semaphore | 資源許可控制 |
CountDownLatch | 執行緒等待計數 |
ExecutorService | 手動 Thread 管理 |
Runnable + 執行緒池,避免手動 Thread。volatile 確保可見性,複合操作用 synchronized/Lock。BlockingQueue。stop/suspend/resume,用 interrupt() 協作式停止。