原来以为tiger已经自带了这种线程池,就是在任务数量超出时能够阻塞住投放任务的线程,主要想用在JMS消息监听。

开始做法:
在ThreadPoolExcecutor中代入new ArrayBlockingQueue(MAX_TASK). 在任务超出时报错:RejectedExecutionException。

后来不用execute方法加入任务,直接getQueue().add(task), 利用其阻塞特性。但是发现阻塞好用了,但是任务没有被处理。一看Queue,晕啊,原来都在里面,任务池就没处理它。看样还是要走任务池。

最后自己重载了一个BlockedThreadPoolExecutor:

 private ReentrantLock pauseLock = new ReentrantLock();
 
private Condition unpaused = pauseLock.newCondition();
 @Override
 
public void execute(Runnable command) {
  pauseLock.lock();
  
try {
   
while (getPoolSize()==getMaximumPoolSize() && getQueue().remainingCapacity()==0)
    unpaused.await();
   
super.execute(command);//放到lock外面的话,在压力测试下会有漏网的!
  }
 catch (InterruptedException e) {
   log.warn(
this, e);
  }
 finally {
   pauseLock.unlock();
  }

 }

 @Override
 
protected void afterExecute(Runnable r, Throwable t) {
  
super.afterExecute(r,t);
  
try{
   pauseLock.lock();
   unpaused.signal();
  }
finally{
   pauseLock.unlock();
  }

 }


多线程程序很容易出错,写好了要拼命的用压力测试,否则问题多多啊~~~
posted on 2005-12-08 18:45  steeven  阅读(3020)  评论(1编辑  收藏  举报