3人参与 • 2025-12-09 • Java
线程池是一种多线程处理形式,它维护着一个线程队列,等待监督管理者分配可并发执行的任务。通过线程池可以避免频繁创建和销毁线程带来的性能开销。
java线程池主要通过java.util.concurrent包下的以下类实现:
// 主要接口和类 executor // 执行器接口 executorservice // 执行服务接口 threadpoolexecutor // 线程池核心实现类 scheduledthreadpoolexecutor // 支持定时调度的线程池 executors // 线程池工厂类
public threadpoolexecutor(
int corepoolsize,
int maximumpoolsize,
long keepalivetime,
timeunit unit,
blockingqueue<runnable> workqueue,
threadfactory threadfactory,
rejectedexecutionhandler handler
)allowcorethreadtimeout(true)设置核心线程超时常见的工作队列实现:
| 队列类型 | 说明 | 特点 |
|---|---|---|
| arrayblockingqueue | 有界队列 | 固定大小,fifo |
| linkedblockingqueue | 无界队列(默认) | 容量为integer.max_value |
| synchronousqueue | 同步队列 | 不存储元素,每个插入操作必须等待另一个线程的移除操作 |
| priorityblockingqueue | 优先级队列 | 具有优先级的无界阻塞队列 |
// 自定义线程工厂示例
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;
}
};当线程池和工作队列都满时,对新任务的处理策略:
| 拒绝策略 | 说明 |
|---|---|
| abortpolicy(默认) | 抛出rejectedexecutionexception异常 |
| callerrunspolicy | 由调用线程(提交任务的线程)执行该任务 |
| discardpolicy | 直接丢弃任务,不抛异常 |
| discardoldestpolicy | 丢弃队列中最旧的任务,然后尝试提交新任务 |
// 线程池工作流程伪代码
public void execute(runnable task) {
if (当前线程数 < corepoolsize) {
创建新线程执行任务;
} else if (工作队列未满) {
将任务加入工作队列;
} else if (当前线程数 < maximumpoolsize) {
创建新线程执行任务;
} else {
执行拒绝策略;
}
}任务提交
↓
当前线程数 < corepoolsize? → 是 → 创建核心线程执行
↓否
工作队列未满? → 是 → 任务入队等待
↓否
当前线程数 < maximumpoolsize? → 是 → 创建非核心线程执行
↓否
执行拒绝策略// 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); // 支持定时和周期性任务
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();
}
}cpu密集型任务
// 线程数 ≈ cpu核心数 + 1 int corepoolsize = runtime.getruntime().availableprocessors() + 1;
io密集型任务
// 线程数 ≈ cpu核心数 * 2 // 或根据具体io等待时间调整 int corepoolsize = runtime.getruntime().availableprocessors() * 2;
// java 1.7+ 支持动态调整参数 executor.setcorepoolsize(10); executor.setmaximumpoolsize(20); executor.setkeepalivetime(120, timeunit.seconds);
java线程池是并发编程的核心组件,合理配置线程池参数对系统性能有重要影响。理解每个参数的含义和工作原理,根据实际业务场景选择合适的配置,是高效使用线程池的关键。在实际开发中,推荐使用threadpoolexecutor手动创建线程池,而不是使用executors的快捷方法,以便更好地控制线程池的行为。
到此这篇关于java线程池核心参数原理及使用指南的文章就介绍到这了,更多相关java线程池参数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论