跪求看看我这个生产者消费者哪里不对?为什么死锁了?
public class WaitAndNotify {
public static void main(String[] args) throws IOException
{
Food food = new Food();
new Thread(new Consumer("消费者一", food)).start();
// new Thread(new Consumer("消费者二", food)).start();
// new Thread(new Consumer("消费者三", food)).start();
//
new Thread(new Producer("生产者一", food)).start();
// new Thread(new Producer("生产者二", food)).start();
// new Thread(new Producer("生产者三", food)).start();
}
}
class Producer implements Runnable
{
private Food food;
private String producerName;
public Producer(String producerName, Food food)
{
this.producerName = producerName;
this.food = food;
}
@Override
public void run()
{
while (true)
{
try
{
food.produce(producerName);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable
{
private Food food;
private String consumerName;
public Consumer(String consumerName, Food food)
{
this.consumerName = consumerName;
this.food = food;
}
@Override
public void run()
{
try
{
food.consume(consumerName);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class Food
{
private AtomicInteger foodNum = new AtomicInteger(0);
public void produce(String s) throws InterruptedException
{
synchronized (this)
{
while (foodNum.get()==5)
{
System.out.println(s+"box is full,size = " + foodNum);
this.wait();
}
foodNum.incrementAndGet();
System.out.println(s+"produce success foodNum = " + foodNum);
this.notifyAll();
}
}
public void consume(String s) throws InterruptedException
{
synchronized (this)
{
while (foodNum.get()==0)
{
System.out.println(s+"box is empty,size = " + foodNum);
this.wait();
}
foodNum.decrementAndGet();
System.out.println(s+"consume success foodNum = " + foodNum);
this.notifyAll();
}
}
}