我需要为家庭作业制作一个消费者生产者问题。我被困在重复线程。仅生产 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();
}
}