JAVA线程池管理的实现

闲来无聊,总结一下自己对线程池理解。这里实现了线程池之外的任务缓冲队列
我看过很多项目,在实现线程池的时候超过缓冲队列大小时放弃最旧的未处理请求
总觉得不太好,现在加上外部缓冲队列看似解决了丢失任务问题确又产生了新的问题
关于异常任务会累积在队列还真不好处理。以后再看吧!!!

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;

/**
 * 线程池管理
 * @author LW
 * @date 2011-2-12
 */
public class ThreadPoolManager {
 
 private static ThreadPoolManager tpm = new ThreadPoolManager();

 // 线程池维护线程的最少数量
 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 ThreadPoolManager() {

 }

 /*
  * 线程池单例创建方法
  */
 public static ThreadPoolManager newInstance() {
  return tpm;
 }

 /*
  * 消息队列检查方法
  */
 private boolean hasMoreAcquire() {
  return !taskQueue.isEmpty();
 }

 /*
  * 向线程池中添加任务方法
  */
 public void addExecuteTask(Runnable task) {
  if (task != null) {
   threadPool.execute(task);
  }
 }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值