연습을 위해 BlockingQueue를 직접 작성했습니다. 메서드에 synchronized 키워드를 사용하지 않으려 고합니다. 대신 ReentrantLock을 사용하고 싶습니다.BlockingQueue ReentrantLock을 사용하여 구현
이 구현을 작성하는 가장 좋은 방법은 무엇입니까? 저는 Java 닌자가 아니며 누군가 제 코드의 오류를 정확하게 지적하고이를 구현하는 더 좋은 방법을 제안 할 수 있다면 크게 감사 할 것입니다.
public class MyBlockingQueue<T> {
private Queue<T> queue;
private AtomicInteger limit = new AtomicInteger(10);
private Lock put_lock = new ReentrantLock();
private Lock take_lock = new ReentrantLock();
private Condition put_condition = put_lock.newCondition();
private Condition take_condition = take_lock.newCondition();
public MyBlockingQueue(AtomicInteger limit){
queue = new LinkedList<T>();
this.limit = limit;
}
public boolean put(T item) throws InterruptedException{
put_lock.lockInterruptibly();
try {
while(queue.size() == limit.get()) {
put_condition.await();
}
put_condition.signal();
queue.add(item);
} finally{
put_lock.unlock();
}
return true;
}
public T take() throws InterruptedException{
take_lock.lockInterruptibly();
try {
while (queue.size() == 0) {
take_condition.await();
}
take_condition.signal();
return queue.poll();
} finally {
take_lock.unlock();
}
}
감사합니다.
사용합니다. 정말로 일을 코딩합니까? 나는 많은 newCondition()을보고 기다리고있다. 조건의 ptr은 저장되지 않으므로 깨울 수 없습니다. – farmer1992
귀하의 요지를 봅니다. 물론 조건을 먼저 저장하고 await() 및 signal()을 호출해야합니다. – Hir
먼저 약속에 따라 코드가 올바르게 작동하는지 확인해야합니다. 모든 동시 플로우를 점검하십시오. 그런 다음 코드를 변경할 수 있습니다. –