// 吃包子 public synchronized void eatBuns() { try { if (Pot.getPotNum() > 0) { // 先取一个包子出来 int temp = pot.removeBuns(); // 判断一下是谁吃的包子 if (Thread.currentThread().getName().equals("小林")) { smallNum++; System.out.println("小林吃了第" + temp + "个包子"); } else { bigNum++; System.out.println("大林吃了第" + temp + "个包子"); } notifyAll(); } else { System.out.println("当前有" + Pot.getPotNum() + "个包子"); // 等待妈妈做包子 System.out.println("等待妈妈做包子吃。。。。。"); wait(); } } catch (Exception e) { e.printStackTrace(); } }
// 生产包子 public synchronized void createBuns() { try { if (Pot.getPotNum() < 10) { System.out.println(Thread.currentThread().getName() + "做了第" + bunsNum + "个包子"); // 妈妈做一个包子放在锅里 pot.addBuns(bunsNum++); notifyAll(); } else { // 等待消费者来消费 wait(); System.out.println("当前有" + Pot.getPotNum() + "个包子"); System.out.println("等待儿子吃包子...."); } } catch (Exception e) { e.printStackTrace(); } }