本文共 1385 字,大约阅读时间需要 4 分钟。
在利用org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
实现请求的慢处理时,我的配置中核心线程数为5,最大线程数为10,但是代码中创建了8个队列放在线程池中,假如我用id
去hash
取模,得到队列集合下标,将数据放到集合的队列中,此时就会出现8个队列中,每个队列都有数据,但只有前5个队列中的请求被处理,后3个队列的请求被搁置。
关键配置及代码:
代码实现如下:
/** * 懒汉式单例可以实现传参的单例初始化 */public class RequestProcessorThreadPool { private volatile static RequestProcessorThreadPool instance = null; private RequestProcessorThreadPool() { } private RequestProcessorThreadPool(ApplicationContext applicationContext) { RequestQueue requestQueue = RequestQueue.getInstance(); ThreadPoolTaskExecutor threadPool = (ThreadPoolTaskExecutor) applicationContext.getBean("deviceBindExecutor"); /** * 给线程池中加入任务队列 */ for (int i = 0; i < 8; i++) { ArrayBlockingQueuequeue = new ArrayBlockingQueue (100); requestQueue.addQueue(queue); threadPool.submit(new RequestProcessorThread(queue)); } } public static RequestProcessorThreadPool getInstance(ApplicationContext applicationContext) { if (instance == null) { synchronized (RequestProcessorThreadPool.class) { if (instance == null) { instance = new RequestProcessorThreadPool(applicationContext); } } } return instance; }}
转载地址:http://ytcsn.baihongyu.com/