在真实项目开发场景中正确使用线程池
这是在项目中正确使用自定义线程池的代码,至于为什么不使用Executors创建线程池,请参考我的上一篇文章:阿里开发手册为什么强制要求使用自定义线程池?
//全局线程池 @Configuration public class ThreadPoolConfig{ /** * 自定义线程池配置 **/ @Bean public TaskExecutor taskExecutor(){ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); //设置核心线程数 executor.setCorePoolSize(10); //设置最大线程数 executor.setMaxPoolSize(20); //设置阻塞队列容量 executor.setQueueCapacity(10); //设置线程存活时间(s) executor.setKeepAliveSeconds(30); //设置默认线程名称 executor.setThreadNamePrefix("my-task-executor-"); //设置拒绝策略(当资源不足时,哪个线程提交哪个线程运行) executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //等待所有任务结束后关闭线程池 executor.setWaitForTasksToCompleteOnShutdown(true); return executor; } }
在需要用到线程池时把taskExecutor这个Bean引入使用即可。