这是生产者消费者模式的作业实现。下面的实现有什么问题。我已经搜索了各种实现,但我无法理解我的错误。在Java中实现生产者消费者
我有一个共享队列
我同步于相同的锁
实施
共享队列生产者和消费者:
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();
}
}
我不知道。哪里不对?什么地方出了错? [Stack Overflow不是心灵读者或水晶球。](http://meta.stackexchange.com/a/128551/133242) – 2012-04-23 02:46:51
作为一般规则,更喜欢'java.util.concurrent'中的实用程序来使用代码等待和通知。(Effective Java,item 69) – 2012-04-23 02:53:11