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;
}
Take() で待機しているスレッドに put() から、またはその逆に通知したい。誰かがこれを行う正しい方法を教えてください。
java.utils の実装を確認したところ、この段階では少し複雑な Condition と ReentrantLocks が使用されています。今のところ、簡単にするために、完全に堅牢でなくても大丈夫です[しかし正しい].
ありがとう !