理解Java线程池基础概念
一、理解Java线程池
1.1 适用场景分析
- 当单个任务的执行耗时较短时
- 需要处理的任务总量较大时
1.2 引入线程池的优势
- 降低因频繁创建和销毁线程所带来的时间损耗及系统资源消耗
- 避免无限制创建线程导致系统内存耗尽的风险
1.3 线程池的四大核心组件
- 1. 线程池管理器(ThreadPool):负责线程池的创建、销毁以及新任务的添加等管理工作;
- 2. 工作线程(PoolWorker):即线程池中的实际工作线程,在无任务时处于等待状态,可循环执行分配到的任务;
- 3. 任务接口(Task):所有任务需实现的统一接口,规定任务入口、执行后收尾工作及状态反馈等规范,供工作线程调度;
- 4. 任务队列(taskQueue):用于暂存尚未处理的任务,提供缓冲机制以平衡生产与消费速度;
1.4 线程池的关键配置参数
ThreadPoolExecutor提供了四个构造方法,前三个均委托给最后一个全参构造器执行
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
// 都调用它
public ThreadPoolExecutor(// 核心线程数
int corePoolSize,
// 最大线程数
int maximumPoolSize,
// 闲置线程存活时间
long keepAliveTime,
// 时间单位
TimeUnit unit,
// 线程队列
BlockingQueue workQueue,
// 线程工厂
ThreadFactory threadFactory,
// 队列已满,而且当前线程数已经超过最大线程数时的异常处理策略
RejectedExecutionHandler handler ) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
核心参数说明
corePoolSize:核心线程数量
- 核心线程即使空闲也会保持存活,不随超时策略关闭
- 当当前线程数少于核心线程数时,即便有空闲线程,池也会优先创建新线程来承接任务
- 若设置allowCoreThreadTimeout=true(默认false),核心线程在空闲超时后也将被终止
maxPoolSize:最大线程数量上限
- 当线程数达到或超过corePoolSize且任务队列已满时,线程池会创建新线程来处理新增任务
- 当线程数达到maxPoolSize且任务队列已满时,线程池将拒绝接收新任务并抛出异常
keepAliveTime:线程空闲存活时间
- 非核心线程空闲时间超过keepAliveTime后将被回收,直至线程总数降至corePoolSize
- 若开启allowCoreThreadTimeout=true,则线程总数可缩减至0
workQueue:阻塞队列,用于存储待执行任务,其选择对线程池性能影响显著,常见选项如下:
- ArrayBlockingQueue
- LinkedBlockingQueue
- SynchronousQueue
关于阻塞队列的详细对比可参考相关文档:java 阻塞队列
threadFactory:线程工厂,用于定制线程的创建过程
rejectedExecutionHandler:任务拒绝处理器,在以下两种情形下触发拒绝逻辑:
- 当前线程数已达maxPoolSize且队列已满,新任务被拒绝
- 当线程池被调用shutdown()后,会等待线程池里的任务执行完毕,再shutdown。如果在调用shutdown()和线程池真正shutdown之间提交任务,会拒绝新任务
触发拒绝时,线程池调用rejectedExecutionHandler进行处理。未指定时默认为AbortPolicy并抛出异常。ThreadPoolExecutor内置以下几种实现:
- AbortPolicy:直接丢弃任务,并抛出运行时异常
- CallerRunsPolicy:由提交任务的线程亲自执行该任务
- DiscardPolicy:静默丢弃任务,无任何操作
- DiscardOldestPolicy:丢弃队列中最老的任务(即最先入队但最后执行的任务),然后尝试重新提交当前任务
- 实现RejectedExecutionHandler接口可自定义拒绝处理逻辑
1.5 Java线程池工具类ExecutorService
- Executors.newCachedThreadPool:创建可缓存线程池,线程数按需增长,空闲线程可灵活回收,若无空闲线程则新建
- Executors.newFixedThreadPool:创建固定大小线程池,控制最大并发数,超额任务进入队列等待
- Executors.newScheduledThreadPool:创建支持定时及周期性任务执行的定长线程池
- Executors.newSingleThreadExecutor:创建单线程化线程池,确保所有任务按指定顺序(FIFO、LIFO或优先级)串行执行
注:Executors仅为工厂类,其返回实例均为ThreadPoolExecutor或ScheduledThreadPoolExecutor
1.6 ExecutorService主要执行方法
- executorService.execute(Runnable):接收Runnable实例,异步执行任务
- executorService.submit(Runnable)
- executorService.submit(Callable)
- executorService.invokeAny(…)
- executorService.invokeAll(…)
execute(Runnable)
该方法接收Runnable实例,并异步执行任务
executorService.execute(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});
executorService.shutdown();
submit(Runnable)
submit(Runnable)与execute(Runnable)的主要区别在于前者返回Future对象,可通过该对象检查任务是否完成,示例如下:
Future future = executorService.submit(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});
future.get(); //returns null if the task has finished correctly.
submit(Callable)
submit(Callable)同样返回Future对象,但其接收Callable实现。Callable的call()方法有返回值,可获取任务结果,而Runnable的run()方法为void无返回值,示例如下:
Future future = executorService.submit(new Callable(){
public Object call() throws Exception {
System.out.println("Asynchronous Callable");
return "Callable Result";
}
});
System.out.println("future.get() = " + future.get());
任务完成后,future.get()将返回Callable的执行结果。注意,此方法会阻塞当前线程直到结果就绪
invokeAny(…)
invokeAny(…)接收Callable集合,不返回Future,而是返回其中任意一个成功完成任务的结果,具体哪个任务先完成不确定
ExecutorService executorService = Executors.newSingleThreadExecutor();
Set> callables = new HashSet>();
callables.add(new Callable() {
public String call() throws Exception {
return "Task 1";
}
});
callables.add(new Callable() {
public String call() throws Exception {
return "Task 2";
}
});
callables.add(new Callable() {
public String call() throws Exception {
return "Task 3";
}
});
String result = executorService.invokeAny(callables);
System.out.println("result = " + result);
executorService.shutdown();
invokeAll(…)
invokeAll(…)与invokeAny(…)类似,也接收Callable集合,但执行后返回包含每个任务对应Future对象的List
List> futures = executorService.invokeAll(callables);
for(Future future : futures){
System.out.println("future.get = " + future.get());
}
executorService.shutdown();
二、在Spring Boot中使用Java线程池ExecutorService
2.1 Spring Boot配置方式
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 数据收集配置,主要作用在于Spring启动时自动加载一个ExecutorService对象.
* @author Bruce
* @date 2026/2/22
* update by Cliff at 2027/11/03
*/
@Configuration
public class ThreadPoolConfig {
@Bean
public ExecutorService getThreadPool(){
return Executors.newFixedThreadPool();
}
}
2.2 使用示例
在@service 中注入 ExecutorService 然后就可以直接用了。
@Autowired
private ExecutorService executorService;
public void test(){
executorService.execute(new Runnable() {
public void run() {
System.out.println("Asynchronous task");
}
});
}
总结
以上即为本文全部内容,希望能为您的学习或工作提供参考。感谢支持,如需了解更多相关内容请查看相关链接