Executor框架:不关心怎么执行,只关心执行什么!任务提交和执行完全解耦。
一、Executor框架层次
Executor (顶层接口)
↓
ExecutorService (生命周期管理)
↓
AbstractExecutorService (模板方法)
↓
ThreadPoolExecutor (核心实现)
Callable/Runnable (任务抽象)
↓
Future (结果获取)
↓
FutureTask (结果实现)
二、核心接口
Executor
public interface Executor {
void execute(Runnable command);
}
最简单实现:
// 直接执行
class DirectExecutor implements Executor {
public void execute(Runnable r) {
r.run(); // 调用者线程执行
}
}
// 新线程执行
class ThreadPerTaskExecutor implements Executor {
public void execute(Runnable r) {
new Thread(r).start();
}
}
ExecutorService
public interface ExecutorService extends Executor {
void shutdown();
List<Runnable> shutdownNow();
boolean isShutdown();
boolean isTerminated();
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
}
三、设计思想
1. 任务抽象
// Runnable:无返回值
Runnable task = () -> System.out.println("Hello");
// Callable:有返回值
Callable<String> task = () -> "Result";
2. 执行策略
// 策略1:单线程串行
ExecutorService executor = Executors.newSingleThreadExecutor();
// 策略2:固定线程池
ExecutorService executor = Executors.newFixedThreadPool(10);
// 策略3:缓存线程池
ExecutorService executor = Executors.newCachedThreadPool();
// 策略4:定时任务
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
3. 结果获取
Future<String> future = executor.submit(() -> "Result");
String result = future.get(); // 阻塞获取结果
四、生命周期管理
RUNNING → SHUTDOWN → STOP → TIDYING → TERMINATED
executor.shutdown(); // 优雅关闭
executor.shutdownNow(); // 立即关闭
executor.awaitTermination(...); // 等待终止
五、使用示例
ExecutorService executor = Executors.newFixedThreadPool(10);
// 提交任务
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 100; i++) {
final int taskId = i;
Future<Integer> future = executor.submit(() -> {
// 任务逻辑
return taskId * 2;
});
futures.add(future);
}
// 获取结果
for (Future<Integer> future : futures) {
Integer result = future.get();
System.out.println(result);
}
executor.shutdown();
下一篇→ Fork/Join框架:分治思想🌲