package com.pool;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 线程队列管理
*
*/
@SuppressWarnings("unchecked")
public class ThreadPoolManager {
private static ThreadPoolManager me = new ThreadPoolManager();
// 线程池维护线程的最少数量
private final static int CORE_POOL_SIZE = 3;
// 线程池维护线程的最大数量
private final static int MAX_POOL_SIZE = 100;
// 线程池维护线程所允许的空闲时间
private final static int KEEP_ALIVE_TIME = 0;
// 线程池所使用的缓冲队列大小,>1000的线程走调度
private final static int WORK_QUEUE_SIZE = 1000;
/** 通知队列 **/
Queue<Runnable> QUEUES = new LinkedList<Runnable>();
public static ThreadPoolManager getInstance() {
return me;
}
final RejectedExecutionHandler handler = new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
QUEUES.offer(r);
}
};
// 管理线程池
final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(WORK_QUEUE_SIZE), this.handler);
// 调度线程池
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
// 访问消息缓存的调度线程
final Runnable accessBufferThread = new Runnable() {
public void run() {
if (hasMoreThreads()) {
System.out.println(QUEUES.size());
Runnable task = QUEUES.poll();
threadPool.execute(task);
}
}
};
//任务调度,超过(MAX_POOL_SIZE+WORK_QUEUE_SIZE)数量的线程,自动走调度执行
final ScheduledFuture taskHandler = scheduler.scheduleAtFixedRate(accessBufferThread, 0, 10, TimeUnit.SECONDS);
private ThreadPoolManager() {
System.out.println("启动线程池...");
}
public void addThread(Thread task) {
threadPool.execute(task);
}
private boolean hasMoreThreads() {
return !QUEUES.isEmpty();
}
}
package com.pool;
import java.util.Date;
/**
*测试调用代码
**/
public class test {
public static void main(String[] args) {
for (int i = 0; i<= 10000;i++){
ThreadPoolManager.getInstance().addThread(new Thread(){
public void run(){
try {
System.out.println(new Date());
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}