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();// 喚醒當前等待的一個線程 } } } }