`
喧嚣之后
  • 浏览: 3134 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

简单的线程池

 
阅读更多
public class SearchLogPool {

// 线程池维护线程的最少数量
private final static int CORE_POOL_SIZE = 5;

// 线程池维护线程的最大数量
private final static int MAX_POOL_SIZE = 20;

// 线程池维护线程所允许的空闲时间
private final static int KEEP_ALIVE_TIME = 180;

// 线程池所使用的缓冲队列大小
private final static int WORK_QUEUE_SIZE = 10000;

// 请求缓冲队列
public Queue<Runnable> msgQueue = new LinkedList<Runnable>();

private static SearchLogPool manager = null;

// 访问请求Request缓存的调度线程
final Runnable accessBufferThread = new Runnable() {
public void run() {
// 查看是否有待定请求,如果有,则添加到线程池中
if (hasMoreAcquire()) {
threadPool.execute(msgQueue.poll());
}
}
};

// handler - 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序
final RejectedExecutionHandler handler = new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
msgQueue.offer(r);
}
};

// 管理线程池
@SuppressWarnings("unchecked")
final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
new ArrayBlockingQueue(WORK_QUEUE_SIZE), this.handler);


/**
* 添加任务
*
* @param task
*/
public void addTask(Runnable task) {

threadPool.execute(task);
}

/**
* 实例化线程池
*
* @param key
* @return
*/
public static synchronized SearchLogPool getInstance() {

if (manager == null) {
System.out.println("实例化线程池~~~~~~~~~~~~~~~~~~~~~~~~~~");
manager = new SearchLogPool();
}

return manager;
}

/**
* 禁止实例化
*/
private SearchLogPool() {
}

private boolean hasMoreAcquire() {
return !msgQueue.isEmpty();
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics