宿題にコンシューマープロデューサー問題を作る必要があります。私はスレッドを繰り返して立ち往生しています。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();
}
}