资源同步与互斥问题(生产者与消费者)

时间:2022-07-19 23:30:46



源码:

package hsx.test;

public class Sample {
 
 public static void main(String[] args) {
  BreadContainer bc = new BreadContainer(50);
  Producer producer1 = new Producer(bc, 50, "producer1");
  Producer producer2 = new Producer(bc, 200, "producer2");
  Consumer consumer1 = new Consumer(bc, 290, "consumer1");
  Consumer consumer2 = new Consumer(bc, 70, "consumer2");
  Consumer consumer3 = new Consumer(bc, 80, "consumer3");
  consumer1.start();
  consumer2.start();
  producer1.start();
  producer2.start();
  consumer3.start();
 }
}

class BreadContainer {
 public static final int MAXNUM = 300;
 private int num = 0;
 public BreadContainer(int num) {
  this.num = num;
 }
 public synchronized void produceBread(String produceName, int produceNum) {
  while(num + produceNum > MAXNUM) {
   System.out.println("要生产的量加上原有的量超过了容器的量,所以" + produceName + "等待消费者消费部分,满足再生产。");
   try {
    wait();
   }
   catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  num += produceNum;
  System.out.println(produceName + "生产了" + produceNum + "个,现在一共有" + num + "个。");
  notifyAll();
 }
 public synchronized void consumeBread(String consumeName, int consumeNum) {
  while(consumeNum > num) {
   System.out.println("要消费的量超过了容器的总量,所以" + consumeName + "等待生产者生产部分,满足再消费。");
   try {
    wait();
   }
   catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  num -= consumeNum;
  System.out.println(consumeName + "消费了" + consumeNum + "个,现在一共有" + num + "个。");
  notifyAll();
 }
}

class Producer extends Thread {
 private BreadContainer bc = null;
 private int produceNum = 0;
 public Producer(BreadContainer bc, int produceNum, String ProduceName) {
  this.bc = bc;
  this.produceNum = produceNum;
  this.setName(ProduceName);
 }
 @Override
 public void run() {
  bc.produceBread(this.getName(), produceNum);
 }
}

class Consumer extends Thread {
 private BreadContainer bc = null;
 private int consumeNum = 0;
 public Consumer(BreadContainer bc, int consumeNum, String consumeName) {
  this.bc = bc;
  this.consumeNum = consumeNum;
  this.setName(consumeName);
 }
 @Override
 public void run() {
  bc.consumeBread(this.getName(), consumeNum);
 }
}


显示结果:

要消费的量超过了容器的总量,所以consumer1等待生产者生产部分,满足再消费。
要消费的量超过了容器的总量,所以consumer2等待生产者生产部分,满足再消费。
producer1生产了50个,现在一共有100个。
consumer2消费了70个,现在一共有30个。
要消费的量超过了容器的总量,所以consumer1等待生产者生产部分,满足再消费。
producer2生产了200个,现在一共有230个。
要消费的量超过了容器的总量,所以consumer1等待生产者生产部分,满足再消费。
consumer3消费了80个,现在一共有150个。
要消费的量超过了容器的总量,所以consumer1等待生产者生产部分,满足再消费。