我用ArrayList当做消息列队接受多个客户端传入的信息
然后另一个类再从这个ArrayList中一个一个的取出处理我现在的问题不知道  怎么才能让这个处理类  知道ArrayList是否有大于1个消息
小弟是初学者 只会做个while死循环while(true)
{
    if(ArrayList多与1)
    {
        处理
    }
}但这样做明显是错误的 CPU占用不堪入目
小弟求解应该怎么设计才是正确的呢
不知道我是否描述的清楚

解决方案 »

  1.   

    JDK1.5的Concurrent中有BlockingQueue可以达到要求,例子如下:
     class Producer implements Runnable {
       private final BlockingQueue queue;
       Producer(BlockingQueue q) { queue = q; }
       public void run() {
         try {
           while(true) { queue.put(produce()); }
         } catch (InterruptedException ex) { ... handle ...}
       }
       Object produce() { ... }
     } class Consumer implements Runnable {
       private final BlockingQueue queue;
       Consumer(BlockingQueue q) { queue = q; }
       public void run() {
         try {
           while(true) { consume(queue.take()); }
         } catch (InterruptedException ex) { ... handle ...}
       }
       void consume(Object x) { ... }
     } class Setup {
       void main() {
         BlockingQueue q = new SomeQueueImplementation();
         Producer p = new Producer(q);
         Consumer c1 = new Consumer(q);
         Consumer c2 = new Consumer(q);
         new Thread(p).start();
         new Thread(c1).start();
         new Thread(c2).start();
       }
     }
      

  2.   

    用ArrayList的话,它有一个size()方法,如下
    int length = ArrayList.size(),用之前先判断它是否为null,这里我也建议用线程去做。
      

  3.   


    对对 我就是这个意思
    但是问题不在这
    问题是 你不知道ArrayList里何时有信息
    你怎样判断?
    就像我 做了一个死循环判断
      

  4.   

    if (list != null && list.size != 0){
      处理} 
      

  5.   

    可以使用迭代器Iterator来做,它有个方法可以判断ArrayList中是否还有元素,hasNext()这个方法
      

  6.   

    这样可以,采用一个停止等待的方式,在list中没有值得时候等待,填入值得时候就去取出来执行。
    LinkedList<String> list = new LinkedList<String>();
        Object synObj = new Object();
        
        public void processList() throws InterruptedException
        {
        
         if(list.isEmpty())
         {
         synchronized (synObj)
    {
    synObj.wait();
    }
         }
        
         doSomthing(list.removeFirst());
        }
        
        public void addList(String str)
        {
         synchronized (synObj)
    {
    list.add(str);
    synObj.notify();
    }
        }
        
        private void doSomthing(String temp)
        {
         // to do your work
        }
      

  7.   

    这样的话,就不会有高CPU的情况发生
      

  8.   


    好神奇啊!
    为什么这样做CPU就很正常???
      

  9.   


    谁能给我解释下  谢谢啦
    为什么我原来这样做就很浪费CPU?
    if (list.size > 0){ 
      处理 } 
      

  10.   

    各位 不好意思 这样做CPU依然很高 是我测试出现问题
      

  11.   

    单独解决CPU占用问题,可以这样:
    while(true) 

        if(ArrayList多与1) 
        { 
            处理 
        } else{
            try{Thread.sleep(10);}catch(Exception e){}
        }