これは、宿題の生産者/消費者パターンの実装です。以下の実装の何が問題になっていますか。私はさまざまな実装をグーグルで検索しましたが、私の何がうまくいかなかったのか理解できません。
共有キューがあります
同じロックでプロデューサーとコンシューマーを同期します
実装
共有キュー:
class SharedQueue{
public static Queue<Integer> queue = new LinkedList<Integer>();
}
プロデューサースレッド:
//The producer thread
class Producer implements Runnable{
public void run()
{
synchronized (SharedQueue.queue)
{
if(SharedQueue.queue.size() >=5)
{
try {
SharedQueue.queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Random r = new Random();
int x = r.nextInt(10);
System.out.println("Inside Producer" + x);
SharedQueue.queue.offer(x);
SharedQueue.queue.notify();
}
}
}
コンシューマースレッド:
class Consumer implements Runnable{
public void run()
{
synchronized (SharedQueue.queue)
{
if(SharedQueue.queue.size() == 0)
{
try {
SharedQueue.queue.wait();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
int k = SharedQueue.queue.remove();
System.out.println("Inside consumer" + k);
}
}
}
メインプログラム
public class ProducerConsumerTest {
public static void main(String[] args)
{
Thread p = new Thread(new Producer());
Thread q = new Thread(new Consumer());
p.start();
q.start();
}
}