분의 시간에 나는 방금 대다수의 메소드에 동기화를 추가했습니다. 스레드 안전성을 보장하기 위해 구현해야 할 것이 있습니까?순환 대기열을 완전히 스레드 안전성으로 만드는 방법
또한이 문제를 해결할 수있는 더 좋은 방법이 있습니까? 분당 한 스레드 만 순환 큐를 한 번에 사용할 수 있습니다. 이는 약간 비효율적 인 것처럼 보입니다.
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