我正在尝试理解 Java 多线程构造,并且正在尝试编写阻塞队列的简单实现。这是我写的代码:
class BlockingBoundedQueue<E>
{
@SuppressWarnings("unchecked")
BlockingBoundedQueue(int size)
{
fSize = size;
fArray = (E[]) new Object[size];
// fBlockingQueue = new ArrayBlockingQueue<E>(size);
}
BlockingQueue<E> fBlockingQueue;
public synchronized void put(E elem)
{
if(fCnt==fSize-1)
{
try
{
// Should I be waiting/locking on the shared array instead ? how ?
wait();
}
catch (InterruptedException e)
{
throw new RuntimeException("Waiting thread was interrupted during put with msg:",e);
}
}
else
{
fArray[fCnt++]=elem;
//How to notify threads waiting during take()
}
}
public synchronized E take()
{
if(fCnt==0)
{
try
{
// Should I be waiting/locking on the shared array instead ? how ?
wait();
}
catch (InterruptedException e)
{
throw new RuntimeException("Waiting thread was interrupted during take with msg:",e);
}
}
return fArray[fCnt--];
//How to notify threads waiting during put()
}
private int fCnt;
private int fSize;
private E[] fArray;
}
我想从 put() 通知在 Take() 中等待的线程,反之亦然。有人可以帮助我以正确的方式做到这一点。
我检查了 java.utils 的实现,它使用了 Condition 和 ReentrantLocks,这对我来说在这个阶段有点复杂。为了简单起见,我现在可以不完全健壮[但正确]。
谢谢 !