1.java给我们自带了4种线程池
newSingleThreadExexcutor:单线程数的线程池(核心线程数=最大线程数=1)
newFixedThreadPool:固定线程数的线程池(核心线程数=最大线程数=自定义)
newCacheThreadPool:可缓存的线程池(核心线程数=0,最大线程数=Integer.MAX_VALUE)
newScheduledThreadPool:支持定时或周期任务的线程池(核心线程数=自定义,最大线程数=Integer.MAX_VALUE
使用方式:
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(() -> {
// 业务逻辑
});
2. 往往我们需要根据业务实际情况自己定义线程池
2.1 创建线程池类:
package com.xxx.xxx.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
public class MyThreadPoolConfig {
@Bean("MyThreadPoolExecutor")
public ThreadPoolExecutor threadPoolExecutor() {
return new ThreadPoolExecutor(
//核心线程数量
16,
//最大线程数量
16,
//最大存活时间
60,
//单位秒
TimeUnit.SECONDS,
//队列类型及大小,
new LinkedBlockingDeque<>(3200),
//线程工厂,构建线程
Executors.defaultThreadFactory(),
//任务具有策略
new ThreadPoolExecutor.AbortPolicy());
}
}
2.2 使用示例:
@Resource
private ThreadPoolExecutor myThreadPoolExecutor;
## 方法中调用
myThreadPoolExecutor.execute(() -> {
// 业务逻辑
})
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端