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;
public class ThreadPoolManager {
/*
* 將構造方法訪問修飾符設爲私有,禁止任意實例化。
*/
private ThreadPoolManager() {}
/*
*實例化私有的靜態成員變量線程池管理對象
*/
private static ThreadPoolManager manager = new ThreadPoolManager();
/*
* 線程池單例創建方法
*/
public static ThreadPoolManager newInstance() {
return manager;
}
// 線程池維護線程的最少數量
private final static int CORE_POOL_SIZE = 3;
// 線程池維護線程的最大數量
private final static int MAX_POOL_SIZE = 10;
// 線程池維護線程所允許的空閒時間
private final static int KEEP_ALIVE_TIME = 0;
// 線程池所使用的緩衝隊列大小
private final static int WORK_QUEUE_SIZE = 10;
// 任務調度週期
private final static int TASK_QOS_PERIOD = 10;
// 任務緩衝隊列
private Queue<Runnable> taskQueue = new LinkedList<Runnable>();
/*
* 線程池超出界線時將任務加入緩衝隊列
*/
final RejectedExecutionHandler handler = new RejectedExecutionHandler() {
public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
taskQueue.offer(task);
}
};
/*
* 將緩衝隊列中的任務重新加載到線程池
*/
final Runnable accessBufferThread = new Runnable() {
public void run() {
if (hasMoreAcquire()) {
threadPool.execute(taskQueue.poll());
}
}
};
/*
* 創建一個調度線程池
*/
final ScheduledExecutorService scheduler = Executors .newScheduledThreadPool(1);
/*
* 通過調度線程週期性的執行緩衝隊列中任務
*/
final ScheduledFuture<?> taskHandler = scheduler.scheduleAtFixedRate(
accessBufferThread, 0, TASK_QOS_PERIOD, TimeUnit.MILLISECONDS);
/*
* 線程池
*/
final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(WORK_QUEUE_SIZE), this.handler);
/*
* 消息隊列檢查方法
*/
private boolean hasMoreAcquire() {
return !taskQueue.isEmpty();
}
/*
* 向線程池中添加任務方法
*/
public void addExecuteTask(Runnable task) {
if (task != null) {
threadPool.execute(task);
}
}
}