Javaマルチスレッド構成を理解しようとしていますが、ブロッキングキューの簡単な実装を記述しようとしています。ブロッキングキューインプリメンテーションでJava Notifyを正しく使用する方法
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()からのテイク()で待機しているスレッドを通知したい:ここで私が書いたコードです。誰かがこれを行う正しい方法で私を助けてくれますか?
私はjava.utilsの実装をチェックしました。この段階で私にとっては少し複雑なConditionとReentrantLocksが使用されていました。私は完全に堅牢ではないのは大丈夫ですが(しかし正しいですが)、今のところ単純です。
ありがとうございます!
thnkxボヘミアン説明のために..私はまだいくつかの質問をしています。どのオブジェクトがロックされているのですか? 2つの異なる方法?また、あなたがループのいくつかの条件をチェックすると言う...どの状態がループ内のスレッドチェックですか? .. notifyAllを呼び出した後、すべてのスレッドが動きますか? – codeObserver
本への違法なリンクを削除し、それをクリーンなものに置き換えた@ Willに感謝します。 – Bohemian
これは何らかのフィッシング攻撃かどうか疑問に思っていました:)答えは詳細でボヘミアンは評判があると思っていましたので、何らかのエラーが発生するはずです。 – codeObserver