傳統 new Thread(runnable).start() 方式存在諸多問題:執行緒建立銷毀開銷大、無統一管理、難以控制並發數量、任務提交與執行耦合。J2SE 5.0 java.util.concurrent 套件從根本上解決了這些痛點。
public interface Executor {
void execute(Runnable command);
}
將「任務提交」與「執行策略」解耦。實作範例:
run()ScheduledExecutorService透過 Executors 工廠快速建立:
// 固定大小執行緒池
ExecutorService fixed = Executors.newFixedThreadPool(3);
// 單執行緒序列化執行
ExecutorService single = Executors.newSingleThreadExecutor();
// 可縮放執行緒池(適合大量短任務)
ExecutorService cached = Executors.newCachedThreadPool();
submit(Runnable/Callable):提交任務,返回 Futureshutdown():優雅關閉,不再接受新任務shutdownNow():嘗試中斷執行中任務awaitTermination(timeout, unit):等待終止invokeAll/InvokeAny:批次提交任務集合ExecutorService pool = Executors.newFixedThreadPool(3);
// 提交任務...
pool.shutdown(); // 停止接受新任務
try {
if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
pool.shutdownNow(); // 強制關閉
if (!pool.awaitTermination(10, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ex) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
// 5 秒後執行一次
scheduler.schedule(() -> System.out.println("一次性"), 5, TimeUnit.SECONDS);
// 每 3 秒固定頻率執行
scheduler.scheduleAtFixedRate(() -> System.out.println("固定頻率"), 0, 3, TimeUnit.SECONDS);
// 上次執行結束後 2 秒再執行
scheduler.scheduleWithFixedDelay(() -> System.out.println("固定延遲"), 0, 2, TimeUnit.SECONDS);
ThreadFactory、RejectedExecutionHandler、勾子方法深入掌握 ThreadPoolExecutor 七大參數配置藝術、Future 非同步編程模式、CompletableFuture(Java 8)組合式非同步、並發集合與同步器實戰應用。