把上面的内容结合起来就是一个SyncQueue的类
public class SyncQueue {
public SyncQueue(int size) {
_array = new Object[size];
_size = size;
_oldest = ;
_next = ;
}
public synchronized void put(Object o) {
while (full()) {
try {
wait();
} catch (InterruptedException ex) {
throw new ExceptionAdapter(ex);
}
}
_array[_next] = o;
_next = (_next + ) % _size;
notify();
}
public synchronized Object get() {
while (empty()) {
try {
wait();
} catch (InterruptedException ex) {
throw new ExceptionAdapter(ex);
}
}
Object ret = _array[_oldest];
_oldest = (_oldest + ) % _size;
notify();
return ret;
}
protected boolean empty() {
return _next == _oldest;
}
protected boolean full() {
return (_next + ) % _size == _oldest;
}
protected Object [] _array;
protected int _next;
protected int _oldest;
protected int _size;
}
可以注意一下get和put方法中while的使用如果换成if是会有问题的这是个很容易犯的错误;)
[] [] []