用Java实现生产者消费者 [英] Implementing producer consumer in Java
本文介绍了用Java实现生产者消费者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是家庭作业的生产者消费者模式的实现。以下实现有什么问题。我已经google了各种实现,但我无法理解我的错误。
This is an implementation of producer consumer pattern for a homework. What's wrong with the below implementation. I have googled for various implementations, but I am not able to understand what went wrong in mine.
我有一个共享队列
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)
with:
while(SharedQueue.queue.size() >= 5)
这个:
if(SharedQueue.queue.size() == 0)
with:
while(SharedQueue.queue.size() == 0)
只需在调用 notify()$后重新检查条件c $ c>。
这篇关于用Java实现生产者消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文