Java 內建語言級多線程支持,比 C/C++ 更直觀。本文通過「四個獨立任務串行 vs 並行」對比,引出線程優勢,系統講解 繼承 Thread、實現 Runnable、Callable+Future、線程池 ExecutorService、同步機制、併發工具類 等核心知識點,並給出生產級代碼範本。
串行執行四個獨立任務(打印、文件操作、數據庫訪問、繪圖)時,每個任務都包含 I/O 等待。單線程需依次等待,總耗時 = 所有任務耗時之和。多線程可並行執行,總耗時 ≈ 最慢任務耗時,極大提升吞吐與響應。
class PrintTask extends Thread {
@Override public void run() {
System.out.println("打印文件: " + Thread.currentThread().getName());
}
}
new PrintTask().start(); // 必須調用 start(),而非 run()
class DbTask implements Runnable {
@Override public void run() {
System.out.println("訪問數據庫: " + Thread.currentThread().getName());
}
}
new Thread(new DbTask()).start();
class CalcTask implements Callable {
@Override public Integer call() throws Exception {
Thread.sleep(1000); // 模擬計算
return 42;
}
}
ExecutorService es = Executors.newSingleThreadExecutor();
Future future = es.submit(new CalcTask());
try {
Integer result = future.get(); // 阻塞直到結果返回
System.out.println("計算結果: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
es.shutdown();
}
// 固定大小線程池(適合 CPU 密集型)
ExecutorService fixed = Executors.newFixedThreadPool(4);
// 緩存線程池(適合大量短生命周期任務)
ExecutorService cached = Executors.newCachedThreadPool();
// 定時/周期任務
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(2);
scheduled.scheduleAtFixedRate(() -> System.out.println("心跳"), 0, 10, TimeUnit.SECONDS);
// 自定義線程池(生產環境推薦,顯式控制隊列、拒絕策略、線程命名)
ThreadPoolExecutor custom = new ThreadPoolExecutor(
4, 8, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100),
new ThreadFactoryBuilder().setNameFormat("biz-%d").build(),
new ThreadPoolExecutor.AbortPolicy()
);
public class Counter {
private int count = 0;
public synchronized void increment() { count++; } // 方法鎖
public void decrement() { synchronized(this) { count--; } } // 塊鎖
}
volatile boolean stopFlag = false;
// 寫入線程
stopFlag = true;
// 讀取線程立即可見
AtomicInteger / LongAdder — 無鎖計數器ConcurrentHashMap — 高併發 MapCountDownLatch — 等待多線程完成CyclicBarrier — 多線程攔截點Semaphore — 信號量限流ReentrantLock / ReadWriteLock — 顯式鎖,支持公平/非公平、可中斷、超時CompletableFuture — 異步編排(Java 8+)BlockingQueue queue = new LinkedBlockingQueue<>(100);
// 生產者
new Thread(() -> {
while (true) {
Task t = produce();
queue.put(t); // 滿則阻塞
}
}).start();
// 消費者
new Thread(() -> {
while (true) {
Task t = queue.take(); // 空則阻塞
consume(t);
}
}).start();
NEW -> RUNNABLE (start()) -> RUNNING (獲取 CPU)
<-> BLOCKED (等待鎖)
<-> WAITING / TIMED_WAITING (wait/sleep/join)
-> TERMINATED (run 結束或異常)
tryLock(timeout)。shutdown() + awaitTermination()。remove() 清理。run() 拋出異常會導致線程悄無聲息死亡,務必 try-catch 並記錄日誌。CompletableFuture.supplyAsync(() -> fetchUser(1))
.thenApply(user -> enrich(user))
.thenAccept(user -> render(user))
.exceptionally(ex -> { log.error(ex); return null; });
從基礎 Thread 到 JUC 工具類,再到 CompletableFuture 異步流,Java 多線程生態已極其完善。選對抽象層級,寫出高併發、可維護的併發代碼。