Spring中线程池的使用 ThreadPoolTaskExecutor
一、配置类代码
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ThreadPoolExecutor; @Configuration public class g02线程 { @Bean("threadName") public ThreadPoolTaskExecutor a (){ //spring框架 自己封装的线程 ThreadPoolTaskExecutor thread = new ThreadPoolTaskExecutor(); // 核心线程数量:线程池创建时候初始化的线程数 thread.setCorePoolSize(4); // 最大线程数,线程池中最大的线程数,只有在缓冲队列满了额之后才会申请超过核心线程数的线程 thread.setMaxPoolSize(10); // 缓冲队列,用来缓冲执行任务的队列 thread.setQueueCapacity(10000); // 允许线程的空闲时间60秒,当超过核心线程出之外的线程在空闲时间到达之后被 thread.setKeepAliveSeconds(60); // 线程池名的前缀,设置好了之后可以方便我们定位处理任务所在的线程池 thread.setThreadNamePrefix("aa--"); // 设置在关机时等待任务完成 thread.setWaitForTasksToCompleteOnShutdown(true); // 该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以保证应用最后能够关闭,而不是阻塞住 thread.setAwaitTerminationSeconds(60); // 设置抛出异常 thread.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 初始化线程池 thread.initialize(); return thread; } }
二、使用类代码
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.annotation.Resource; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class 线程池的使用 { @Resource(name="threadName") private ThreadPoolTaskExecutor threadPoolTaskExecutor; // 任务代码:模拟业务场景 public void taskCode(String req){ // 线程中执行的任务 CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> { return req + "任务代码执行中"; }, threadPoolTaskExecutor); // 获取到线程中返回的数据 try { String s = stringCompletableFuture.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!