这是一篇关于生产者消费者模式的实现作业。下面的实现有什么问题。我在谷歌上搜索了各种实现,但我无法理解我的问题出在哪里。
I have a shared queue
I synchronize the producer and consumer on the same lock
实现
共享队列:
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();
}
}
最佳答案
尝试替换:
if(SharedQueue.queue.size() >= 5)
与:
while(SharedQueue.queue.size() >= 5)
还有这个:
if(SharedQueue.queue.size() == 0)
与:
while(SharedQueue.queue.size() == 0)
只是为了在调用notify()
后重新检查条件。
关于java - 用Java实现生产者消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10274223/