有人能帮我检查一下这段代码吗?为了简单起见,我还没有实现所有的方法。
/**
* Implements a blocking bounded queue from a given non-blocking unbounded queue implementation
*/
abstract class DerivedQueue<E> implements Queue<E>
{
DerivedQueue(Queue<E> queue, int size)
{
if(queue==null | size <0)
{
throw new RuntimeException("Bad Input");
}
fQueue = queue;
fSize = size;
}
Queue<E> fQueue;
int fSize;
int fCnt;
@Override
public boolean addAll(Collection<? extends E> arg0)
{
return false;
}
@Override
public boolean isEmpty()
{
return (fCnt==0);
}
public E remove()
{
if(fCnt==0)
{
try
{
wait();
}
catch (InterruptedException e)
{
throw new RuntimeException("Waiting thread was interrupted during remove with msg:",e);
}
}
E elem = fQueue.remove();
fCnt--;
notifyAll();
return elem;
}
@Override
public boolean add(E elem)
{
if(fCnt == fSize)
{
try
{
wait();
}
catch (InterruptedException e)
{
throw new RuntimeException("Waiting thread was interrupted during remove with msg:",e);
}
}
return fQueue.add(elem);
}
}公开问题:
notifyAll()会导致多个等待线程同时检查while()条件,因此有可能在while得到满足之前,已经有2个线程退出它,从而导致outOfBound异常?或者这些方法完全需要标记为synchronized,相反,我可以使用synchronized块来读取或写入数组的一部分,而约束和等待的检查可能保持不同步?notifyAll通知所有这些线程。发布于 2011-06-28 09:02:22
在我的oppinion类中,应该始终首先定义变量--甚至在构造函数之前。另一个问题:为什么变量以f作为前缀?改名为不那么令人困惑的东西。尤其是fSize和fCnt非常接近。(暗示maxSize和currentSize)。
发布于 2011-06-30 06:25:17
您的实现不是threadsafe:假设队列是空的,需要删除元素的几个线程正在等待。然后添加一个元素并通知所有等待的线程。然后,他们都尝试在没有进一步测试的情况下删除一个元素,该元素只对第一个线程起作用,下一个线程将导致下流。几个等待添加的线程的情况相同。
因此,要么修复这个问题,要么添加一个带有“”警告的注释。
发布于 2011-07-13 08:47:17
我还可以看到上面的代码还有两个问题:
fCurrrentCnt++方法中缺少对add的增量。remove,然后调用add,这将导致死锁。两个人都会互相等待。https://codereview.stackexchange.com/questions/3157
复制相似问题