我们可以通过如下代码创建一个线程池:
https://www.jianshu.com/p/f030aa5d7a28
线程池参数详解:
https://blog.csdn.net/qq_50652600/article/details/121212661
https://www.jianshu.com/p/e20c0ba4328c
@Component
public class RecommendFilterThreadPool {
static ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("threadname-threadpool").build();
private static volatile ThreadPoolExecutor threadPoolExecutor = null;
//Init threadpool
public static ThreadPoolExecutor getThreadPool(){
if(threadPoolExecutor == null){
synchronized (SkuMatchThreadPool.class){
if(threadPoolExecutor == null){
threadPoolExecutor = new ThreadPoolExecutor(
100,
100,
30L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(500),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
throw new RuntimeException("线程池打满");
}
});
}
}
}
return threadPoolExecutor;
}
//Shut down threadPool
@PreDestroy
public void shutDownThreadPool(){
if(threadPoolExecutor != null){
threadPoolExecutor.shutdown();
}
}
}
在高并发场景会出现线程池被打满情况,在网上找到一个遇到同样问题的案例:
https://www.jianshu.com/p/8e735d25c1de
线程池的种类:
https://www.cnblogs.com/zhuyeshen/p/12683649.html
线程池参数详解:
https://blog.csdn.net/qq_35909080/article/details/87002367
https://www.cnblogs.com/it-deepinmind/p/13072269.html
补充纠正一下解决方案:
在遇到线程池被打满,有大量队列排队的情况,首先应该考虑是把超时时间设短,这样拿不到数据直接释放线程资源,第二个是考虑为什么请求会超时,是否可以找到解决方案使获取数据不超时,关于将线程池线程数增大我觉得不是合理的解决方案,因为请求超时,怎么设置都会超时,反而造成资源占用严重,影响系统整体性能