一、线程池概述
1.1 什么是线程池
线程池是一种多线程处理形式,它维护着一个线程队列,等待监督管理者分配可并发执行的任务。通过线程池可以避免频繁创建和销毁线程带来的性能开销。
1.2 线程池的优势
- 降低资源消耗:重复利用已创建的线程,减少线程创建和销毁的开销
- 提高响应速度:任务到达时,无需等待线程创建即可立即执行
- 提高线程的可管理性:统一分配、调优和监控线程
- 提供更强大的功能:支持定时执行、定期执行等功能
二、线程池核心类
java线程池主要通过java.util.concurrent包下的以下类实现:
// 主要接口和类 executor // 执行器接口 executorservice // 执行服务接口 threadpoolexecutor // 线程池核心实现类 scheduledthreadpoolexecutor // 支持定时调度的线程池 executors // 线程池工厂类
三、threadpoolexecutor核心参数详解
3.1 构造方法
public threadpoolexecutor(
int corepoolsize,
int maximumpoolsize,
long keepalivetime,
timeunit unit,
blockingqueue<runnable> workqueue,
threadfactory threadfactory,
rejectedexecutionhandler handler
)3.2 七大核心参数
1.corepoolsize(核心线程数)
- 线程池中保持存活的线程数量(即使空闲)
- 默认情况下,核心线程不会超时被回收
- 可以通过
allowcorethreadtimeout(true)设置核心线程超时
2.maximumpoolsize(最大线程数)
- 线程池允许创建的最大线程数量
- 当工作队列满且当前线程数小于最大线程数时,会创建新线程
3.keepalivetime(线程空闲时间)
- 非核心线程空闲时的存活时间
- 当线程空闲时间超过该值且当前线程数大于核心线程数时,线程会被回收
4.unit(时间单位)
- keepalivetime的时间单位
- 如:timeunit.seconds、timeunit.milliseconds
5.workqueue(工作队列)
常见的工作队列实现:
| 队列类型 | 说明 | 特点 |
|---|---|---|
| arrayblockingqueue | 有界队列 | 固定大小,fifo |
| linkedblockingqueue | 无界队列(默认) | 容量为integer.max_value |
| synchronousqueue | 同步队列 | 不存储元素,每个插入操作必须等待另一个线程的移除操作 |
| priorityblockingqueue | 优先级队列 | 具有优先级的无界阻塞队列 |
6.threadfactory(线程工厂)
- 用于创建新线程
- 可以设置线程名称、优先级、守护线程等属性
// 自定义线程工厂示例
threadfactory customthreadfactory = new threadfactory() {
private final atomicinteger threadnumber = new atomicinteger(1);
@override
public thread newthread(runnable r) {
thread thread = new thread(r);
thread.setname("mythread-" + threadnumber.getandincrement());
thread.setdaemon(false);
thread.setpriority(thread.norm_priority);
return thread;
}
};7.handler(拒绝策略)
当线程池和工作队列都满时,对新任务的处理策略:
| 拒绝策略 | 说明 |
|---|---|
| abortpolicy(默认) | 抛出rejectedexecutionexception异常 |
| callerrunspolicy | 由调用线程(提交任务的线程)执行该任务 |
| discardpolicy | 直接丢弃任务,不抛异常 |
| discardoldestpolicy | 丢弃队列中最旧的任务,然后尝试提交新任务 |
四、线程池工作原理
4.1 任务处理流程
// 线程池工作流程伪代码
public void execute(runnable task) {
if (当前线程数 < corepoolsize) {
创建新线程执行任务;
} else if (工作队列未满) {
将任务加入工作队列;
} else if (当前线程数 < maximumpoolsize) {
创建新线程执行任务;
} else {
执行拒绝策略;
}
}4.2 状态流转图
任务提交
↓
当前线程数 < corepoolsize? → 是 → 创建核心线程执行
↓否
工作队列未满? → 是 → 任务入队等待
↓否
当前线程数 < maximumpoolsize? → 是 → 创建非核心线程执行
↓否
执行拒绝策略五、常见线程池类型
5.1 通过executors创建的线程池(不建议使用)
// 1. 固定大小线程池 executorservice fixedthreadpool = executors.newfixedthreadpool(10); // 特点:核心线程数=最大线程数,使用无界队列 // 2. 单线程线程池 executorservice singlethreadpool = executors.newsinglethreadexecutor(); // 特点:只有一个线程,任务顺序执行 // 3. 缓存线程池 executorservice cachedthreadpool = executors.newcachedthreadpool(); // 特点:核心线程数为0,最大线程数为integer.max_value,使用同步队列 // 4. 定时任务线程池 scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool(5); // 支持定时和周期性任务
5.2 创建自定义线程池(推荐)
threadpoolexecutor executor = new threadpoolexecutor(
5, // corepoolsize
10, // maximumpoolsize
60l, // keepalivetime
timeunit.seconds, // unit
new arrayblockingqueue<>(100), // workqueue
executors.defaultthreadfactory(), // threadfactory
new threadpoolexecutor.abortpolicy() // handler
);六、线程池使用示例
public class threadpoolexample {
public static void main(string[] args) {
// 创建线程池
threadpoolexecutor executor = new threadpoolexecutor(
2, 5, 60, timeunit.seconds,
new arrayblockingqueue<>(10),
new customthreadfactory(),
new threadpoolexecutor.callerrunspolicy()
);
// 提交任务
for (int i = 1; i <= 20; i++) {
final int taskid = i;
executor.execute(() -> {
system.out.println(thread.currentthread().getname() +
" 执行任务 " + taskid);
try {
thread.sleep(1000);
} catch (interruptedexception e) {
thread.currentthread().interrupt();
}
});
}
// 监控线程池状态
monitorthreadpool(executor);
// 优雅关闭
executor.shutdown();
try {
if (!executor.awaittermination(60, timeunit.seconds)) {
executor.shutdownnow();
}
} catch (interruptedexception e) {
executor.shutdownnow();
thread.currentthread().interrupt();
}
}
// 自定义线程工厂
static class customthreadfactory implements threadfactory {
private final atomicinteger counter = new atomicinteger(1);
@override
public thread newthread(runnable r) {
thread thread = new thread(r);
thread.setname("customthread-" + counter.getandincrement());
thread.setdaemon(false);
thread.setpriority(thread.norm_priority);
return thread;
}
}
// 监控线程池状态
private static void monitorthreadpool(threadpoolexecutor executor) {
new thread(() -> {
while (!executor.isterminated()) {
system.out.println("=== 线程池状态监控 ===");
system.out.println("核心线程数: " + executor.getcorepoolsize());
system.out.println("当前线程数: " + executor.getpoolsize());
system.out.println("活跃线程数: " + executor.getactivecount());
system.out.println("队列大小: " + executor.getqueue().size());
system.out.println("完成任务数: " + executor.getcompletedtaskcount());
system.out.println("总任务数: " + executor.gettaskcount());
system.out.println("========================\n");
try {
thread.sleep(3000);
} catch (interruptedexception e) {
thread.currentthread().interrupt();
break;
}
}
}).start();
}
}七、最佳实践与注意事项
7.1 线程池配置建议
cpu密集型任务
// 线程数 ≈ cpu核心数 + 1 int corepoolsize = runtime.getruntime().availableprocessors() + 1;
io密集型任务
// 线程数 ≈ cpu核心数 * 2 // 或根据具体io等待时间调整 int corepoolsize = runtime.getruntime().availableprocessors() * 2;
7.2 注意事项
- 避免使用无界队列:可能导致内存溢出
- 合理设置拒绝策略:根据业务需求选择
- 优雅关闭线程池:使用shutdown()和shutdownnow()
- 监控线程池状态:定期检查线程池运行状况
- 为线程命名:便于问题排查
7.3 线程池参数动态调整
// java 1.7+ 支持动态调整参数 executor.setcorepoolsize(10); executor.setmaximumpoolsize(20); executor.setkeepalivetime(120, timeunit.seconds);
八、总结
java线程池是并发编程的核心组件,合理配置线程池参数对系统性能有重要影响。理解每个参数的含义和工作原理,根据实际业务场景选择合适的配置,是高效使用线程池的关键。在实际开发中,推荐使用threadpoolexecutor手动创建线程池,而不是使用executors的快捷方法,以便更好地控制线程池的行为。
到此这篇关于java线程池核心参数原理及使用指南的文章就介绍到这了,更多相关java线程池参数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论