您的位置:首页 > 理论基础 > 数据结构算法

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

2011-03-23 10:14 337 查看
这两天看了看池,循环队列没好好学习,算是重新来过了

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: