[英]Program of consumer Producer
我需要为家庭作业制作一个消费者生产者问题。 我被困重复线程。 仅产生1个对象,并且仅消耗1个对象。 如果对象存在于数组中,那么生产者将不生产并等到消费者消费它。
class PC extends Thread{
static int i=1;
static int storage[]=new int[1];
String info;
PC(String _info)
{
this.info=_info;
}
public synchronized void consume()
{
if(storage[0]==-1)
{
try {
System.out.println("C: 0" );
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
}
else
{
System.out.println("C: " + storage[0]);
storage[0]=-1;
i++;
notify();
}
}
public synchronized void prod()
{
if(storage[0]!=-1)
{
try {
System.out.println("P: 0" );
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
}
else
{
storage[0]=i;
System.out.println("P: " + storage[0]);
notify();
}
}
public void run()
{
if(info=="producer"){
prod();
}
else
consume();
}
public static void main(String args[])
{
storage[0]=-1;
PC consumer =new PC("consumer");
PC producer =new PC("producer");
consumer.start();
producer.start();
}
}
使用将由producer
和consumer
线程共享的BlockingQueue
。 如果您需要更多帮助,请告诉我。
您需要在run()
方法中有一个循环。 可以使用while-loop
,也可以使用for-loop
来生成或使用一定数量的商品。
也要注意String比较。
仅产生1个对象,并且仅消耗1个对象。
是的,是的:
public void run() { if(info=="producer"){ prod(); } else consume(); }
(您还可以在不同的对象上进行同步,因此线程将不会共享监视器。这意味着类变量“存储”也不受保护。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.