在剛剛添加的同步到大多數方法的時刻,因爲看起來沒有它,這些方法不是線程安全的。還有什麼我需要實現以確保它是線程安全的。如何使循環隊列完全線程安全
此外,有沒有更好的方式去做這件事。當時只有一個線程可以同時使用循環隊列,這似乎有點低效。
class CircularQueue<T> implements Iterable<T>{
private T queue[];
private int head, tail, size;
@SuppressWarnings("unchecked")
public CircularQueue(){
queue = (T[])new Object[20];
head = 0; tail = 0; size = 0;
}
@SuppressWarnings("unchecked")
public CircularQueue(int n){ //assume n >=0
queue = (T[])new Object[n];
size = 0; head = 0; tail = 0;
}
public synchronized boolean join(T x){
if(size < queue.length){
queue[tail] = x;
tail = (tail+1)%queue.length;
size++;
return true;
}
else return false;
}
public synchronized T top(){
if(size > 0)
return queue[head];
else
return null;
}
public synchronized boolean leave(){
if(size == 0) return false;
else{
head = (head+1)%queue.length;
size--;
return true;
}
}
public synchronized boolean full(){return (size == queue.length);}
public boolean empty(){return (size == 0);}
public Iterator<T> iterator(){
return new QIterator<T>(queue, head, size);
}
private static class QIterator<T> implements Iterator<T>{
private T[] d; private int index;
private int size; private int returned = 0;
QIterator(T[] dd, int head, int s){
d = dd; index = head; size = s;
}
public synchronized boolean hasNext(){ return returned < size;}
public synchronized T next(){
if(returned == size) throw new NoSuchElementException();
T item = (T)d[index];
index = (index+1) % d.length;
returned++;
return item;
}
public void remove(){}
}
}
任何意見或幫助,你可以給我們將不勝感激!
如果你想多線程的全部好處,你可以考慮去[免費](https://codereview.stackexchange.com/questions/12691/o1-lock-free-container)。 – OldCurmudgeon