一.線程池管理類
/**
* 線程池管理類
*/
public class ThreadPoolFactory
{
private static final Log logger = LogFactory.getLog(ThreadPoolFactory.class);
/**
* 放入管理線程池線程間隔時間
*/
private final static int PUT_DEFAULTPOOL_INTERVAL = 3;
/**
* 線程池保持對象
*/
private static Map<String, ThreadPool> poolMap = new HashMap<String, ThreadPool>();
/**
* 請求Request緩衝隊列(緩存隊列滿時)
*/
public static final Queue<Runnable> msgQueue = new ConcurrentLinkedQueue<Runnable>();
static
{
// 訪問請求Request緩存的調度線程
final Runnable accessBufferThread = new Runnable()
{
public void run()
{
// 查看是否有待定請求,如果有,則添加到線程池中
if (!msgQueue.isEmpty())
{
Runnable r = msgQueue.poll();
logger.error("緩存隊列線程放入默認線程池執行" + r);
getThreadPool("defaultThreadPool").execute(r);
}
}
};
// 調度線程池
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
// 定時調度
scheduler.scheduleAtFixedRate(accessBufferThread, 0, PUT_DEFAULTPOOL_INTERVAL, TimeUnit.SECONDS);
}
/**
* 根據key取得對應線程池實例
*
*/
public static ThreadPool getThreadPool(String key)
{
ThreadPool obj = null;
if (StringUtils.isNotBlank(key))
{
obj = poolMap.get(key);
if (obj == null)
{
synchronized (ThreadPoolFactory.class)
{
if (obj == null)
{
logger.error("線程池" + key + "不存在,已被創建");
obj = new ThreadPool(key);
poolMap.put(key, obj);
}
}
}
else
{
logger.info("線程池" + key + "存在,已返回");
}
}
return obj;
}
/**
* 靜態工廠不允許被實例化
*/
private ThreadPoolFactory()
{
}
}
二.線程池類
/**
* 線程池類
*/
public class ThreadPool
{
/**
* 日誌組件
*/
private final Log logger = LogFactory.getLog(ThreadPool.class);
/**
* 線程池名字
*/
private String name;
/**
* 線程池維護線程的最少數量
*/
private final static int CORE_POOL_SIZE = 5;
/**
* 線程池維護線程的最大數量
*/
private final static int MAX_POOL_SIZE = 100;
/**
* 線程池維護線程所允許的空閒時間
*/
private final static int KEEP_ALIVE_TIME = 180;
/**
* 線程池所使用的緩衝隊列大小
*/
private final static int WORK_QUEUE_SIZE = 5000;
/**
* handler - 由於超出線程範圍和隊列容量而使執行被阻塞時所使用的處理程序
*/
final RejectedExecutionHandler handler = new RejectedExecutionHandler()
{
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor)
{
logger.error(name + "已滿, 線程被放入公共隊列中等待執行 " + r);
boolean result = ThreadPoolFactory.msgQueue.offer(r);
if (!result)
{
logger.error("放入等待隊列失敗,系統發生嚴重錯誤");
}
}
};
/**
* 線程池
*/
private ThreadPoolExecutor threadPool;
/**
* 構造方法
*/
ThreadPool(String name)
{
logger.error("CORE_POOL_SIZE=" + CORE_POOL_SIZE + ", MAX_POOL_SIZE=" + MAX_POOL_SIZE + ", KEEP_ALIVE_TIME="
+ KEEP_ALIVE_TIME + ", WORK_QUEUE_SIZE=" + WORK_QUEUE_SIZE);
this.name = name;
threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(WORK_QUEUE_SIZE), this.handler);
}
public void execute(Runnable task)
{
threadPool.execute(task);
}
}