Java POJO:处理服务器请求对象队列的策略

现在我在决定处理我发送到服务器的请求对象的最佳方式时被撕毁了。换句话说,我在应用中有跟踪请求对象,例如展示和点击跟踪。具有极低有效负载的简单请求。我的应用程序中有些地方需要跟踪的对象同时出现(我必须跟踪最多三个并发对象),因此每次所述对象都可见时,我必须创建一个跟踪请求每个人的对象。 现在我已经知道我可以轻松创建一个单例队列线程,它将这些对象添加到一个向量中,我的线程要么在主循环中处理它们,要么在队列上调用wait,直到我们有对象要处理。虽然这听起来像是一个明确的解决方案,但队列可以累积到数十个,这有时很麻烦,因为它为每个请求建立一个连接,因此它不会同时运行。 我想到的是创建一个线程池,它允许我通过信号量创建两个并发连接,并处理包含我的跟踪事件请求的线程对象。换句话说,我想创建一个函数来创建一个新的线程对象并将其添加到Vector中,其中线程池将遍历该组线程并一次处理两个线程。我知道我可以创建一个像这样添加对象的函数:
public boolean addThread(Runnable r){
synchronized(_queue){
    while(!dead){
       _queue.addElement(r);
       //TODO: How would I notify my thread pool object to iterate through the list to process the queue? Do I call notify on the queue object, but that would only work on a thread right??
       return true
    }
    return false;
}
我想知道的是线程本身将如何执行。如何在向列表添加线程后编写将执行线程池的函数?此外,由于信号量将在第二次连接后阻塞,是否会锁定我的应用程序,直到有一个打开的插槽,或者它是否只是在循环列表时锁定在线程池对象中? 与往常一样,由于我的目标是J2ME / Blackberry环境,因此只接受1.5之前的答案,因此没有Generics或Concurrent包中的任何类。 编辑:所以我认为这应该看起来或多或少:
class MyThreadPool extends Thread{

  private final Vector _queue = new Vector();
  private CappedSemaphore _sem;
  public MyWaitingThread (){
      _sem = new CappedSemaphore(2);
      this.start();
  }
  public void run(){
     while(!dead){
        Runnable r = null;
        synchronized(_queue){
          if(_queue.isEmpty()){
            _queue.wait();
          } else {
            r = _queue.elementAt(0);
            _queue.removeElement(0);
          }
       }
       if(r != null){
          _sem.take();
          r.run();
          _sem.release();
       }
    }
 }
 public boolean addThread(Runnable r){
   synchronized(_queue){
   if(!dead){
     _queue.addElement(r);
     _queue.notifyAll();
     return true
   }
   return false;
 }
}
    
已邀请:
你想要做什么,在线程方面让每个线程在队列上等待。例如
class MyWaitingThread extends Thread{

   private final Queue _queue;
   public MyWaitingThread (Queue _queue){
      this._queue = _queue;
   }
   public void run(){
      while(true){
       Runnable r = null;
       synchronized(_queue){
            if(_queue.isEmpty())
                _queue.wait();
            else
               r = queue.pop();
        }
      if(r != null) r.run();
      }
   }
}
在你的其他逻辑中它看起来像:
public void addThread(Runnable r){
     if(!dead){
       synchronized(_queue){
         _queue.addElement(r);
         _queue.notifyAll();
       }
     }
}
_queue.notifyAll
将唤醒所有等待
_queue
实例的线程。另外,请注意我将
while(!dead)
移动到同步块之外并将其更改为
if(!dead)
。我可以想象保持它原来的方式它不会像你希望的那样工作。     

要回复问题请先登录注册