悲剧了(愈发的感觉 数据结构的重要性,一定要把数据结构的思想整明白)

这两天看了看池,循环队列没好好学习,算是重新来过了

protected int _next;
protected int _oldest;
关于队列满的情况判断,所以队列中只能存储size-1个值,如果使用
return (_next) % _size == _oldest;的话,初始就full了,而用next+1的话,
最后一个位置就不能够填上,等到oldest改变(即池中的数据取出之后才开始
继续填充)


package tests;

public class SyncQueue {
        protected Object[] _array;
        protected int _next;
        protected int _oldest;
        protected int _size;
   
    public SyncQueue(int size) {
           _array = new Object[size];
           _size = size;
           _oldest = 0;
           _next = 0;
        }

        public synchronized void put(Object o) throws

ExceptionAdapter {
           while (full()) {
               try {
                   System.out.print("full;&&&&&&&wait\n");
                  wait();
               } catch (InterruptedException ex) {
                   System.out.print("Exception");
                  throw new ExceptionAdapter(ex);
               }
           }
           _array[_next] = o;
           System.out.print("next="+_next+"\n");
           _next = (_next + 1) % _size;
           notify();
        }

        public synchronized Object get() {
           while (empty()) {
               try {
                   System.out.print("empty;&&&&&&&wait\n");
                  wait();
               } catch (InterruptedException ex) {
                  try {
                    throw new ExceptionAdapter

(ex);
                } catch (ExceptionAdapter e) {
                    // TODO Auto-generated

catch block
                    e.printStackTrace();
                }
               }
           }
           Object ret = _array[_oldest];
           _oldest = (_oldest + 1) % _size;
           notify();
           return ret;
        }

        protected boolean empty() {
           return _next == _oldest;
        }

        protected boolean full() {
           return (_next+1) % _size == _oldest;
        }
}

posted on 2011-03-23 10:14  songqiuming  阅读(158)  评论(0编辑  收藏  举报

导航