package com.hx.phip.uti; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 创建线程池的,主要避免线程队列超,导致服务器爆了 */ public class ExecutorServiceTool { /**log4j日志*/ private static Logger logger = LoggerFactory.getLogger(ExecutorServiceTool.class.getName()); /**线程池-获取队列的*/ private ThreadPoolExecutor threadPool; /**最大队列*/ private int maxQueue; public ExecutorServiceTool() { } public ExecutorServiceTool(int initTread, int maxQueue) { createThread(initTread,maxQueue); } /**创建线程池 * @param initTread 初始化线程池 * @param maxQueue 最大队列新增队列,注意:这里只做传值,不限制真对 * 线程池限制队列,因为限制了会报错,导致数据丢失 * @return */ public ThreadPoolExecutor createThread(int initTread,int maxQueue){ this.threadPool = new ThreadPoolExecutor(initTread, initTread, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); this.maxQueue = maxQueue; return this.threadPool; } /**针对最大的队列,如果没有超过返回是false的,超过就返回是true的 * 单返回true的时候,就不要传入队列了 * @param sleepMillisecond 睡眠,毫秒秒,如果是空的,那么直接返回 * @return */ public boolean noRund(Integer sleepMillisecond){ if(threadPool.getQueue().size() > maxQueue){ if(sleepMillisecond != null && sleepMillisecond > 0){ try{ Thread.sleep(sleepMillisecond); }catch (Exception e){ logger.error("线程池开启睡眠失败!"); } } return true; }else{ return false; } } /**关闭*/ public void shutdown(){ this.threadPool.shutdown(); } /****************************************************************************************/ public int getMaxQueue() { return maxQueue; } public void setMaxQueue(int maxQueue) { this.maxQueue = maxQueue; } public ThreadPoolExecutor getThreadPool() { return threadPool; } public void setThreadPool(ThreadPoolExecutor threadPool) { this.threadPool = threadPool; } }