package com.reveiew;/* * 多个生产者多个消费者,只有5个包子 * 跟第一,第二的例子不同的是,不是new一个对象调用锁,而是用BaoZi.calss直接调用锁 */public class MoreProuduceCustomMoreBaoZi {public static void main(String[] args) {Produce3 p = new Produce3();p.setName("生产者");Produce3 p2 = new Produce3();p2.setName("生产者2");Produce3 p3 = new Produce3();p3.setName("生产者3");customer3 c = new customer3();c.setName("消费者");customer3 c2 = new customer3();c2.setName("消费者2");customer3 c3 = new customer3();c3.setName("消费者3");p.start();c.start();p2.start();c2.start();p3.start();c3.start();}}class BaoZi3 {public static int num = 0;}class Produce3 extends Thread {public void run() {while (true) {synchronized (BaoZi3.class) {while (BaoZi3.num >=5) {// 等着消费者消费.生产者应该等待。需要用锁去调用wait方法。try {BaoZi3.class.wait();// wait会释放锁//哪个线程执行就是哪个线程等} catch (InterruptedException e) {e.printStackTrace();}}BaoZi3.num++;try {Thread.sleep(1000);// sleep不会释放锁} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + "生产一个包子"+"剩余包子"+BaoZi3.num);BaoZi3.class.notifyAll();// 唤醒消费者}}}}class customer3 extends Thread {public void run() {while (true) {synchronized (BaoZi3.class) {while (BaoZi3.num == 0) {try {BaoZi3.class.wait();} catch (InterruptedException e) {e.printStackTrace();}}BaoZi3.num--;try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + "消费一个包子"+"剩余包子"+BaoZi3.num);// 唤醒消费者BaoZi3.class.notifyAll();// 唤醒当前等待的一个线程}}}}