作者在 2016-01-27 20:02:10 发布以下内容
在资源的同步互斥中,生产者-消费者的含义是,系统中有很多生产者和消费者同时工作, 生产者负责 生产需要的资源,消费者消耗资源。 当消费者消费资源时,如果资源 不足,则等待。反之当生产者生产资源 时,如果资源已经满足需要,则也要等待该生产。同一时刻只能有一个生产者或消费者进行操作。
package com.qun;
public class Theaddemo {
class BreadContainer {
public static final int maxNum = 600;
private int num;
public BreadContainer() {
}
public BreadContainer(int num) {
this.num = num;
}
public synchronized void produceBread(int produceNum,
String producerName) {
while (num + produceNum > maxNum) {
System.out.println(producerName + "要生产" + produceNum + "个,当前"
+ num + "个,充足,不需要生产," + producerName + "去等待!");
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
num = num + produceNum;
System.out.println(producerName + "生产了" + produceNum + "个,现有" + num
+ "个。");
notifyAll();
}
public synchronized void consumeBread(int consumeNum,
String consumerName) {
while (consumeNum > num) {
System.out.println(consumerName + "要消费" + consumeNum
+ "个,由于 现在只有" + num + "个, " + consumerName + "于是去等待");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num = num - consumeNum;
System.out.println(consumerName + "消费了" + consumeNum + "个, 现在还剩下"
+ num + "个");
this.notifyAll();
}
}
class Producer extends Thread {
private int produceNum;
private BreadContainer bc;
// private String producerName;
public Producer() {
}
public Producer(int produceNum, BreadContainer bc, String producerName) {
this.produceNum = produceNum;
this.bc = bc;
this.setName(producerName);
}
public void run() {
bc.produceBread(produceNum, this.getName());
}
}
class Consumer extends Thread {
private int consumeNum;
private BreadContainer bc;
public Consumer() {
}
public Consumer(int consumeNum, BreadContainer bc, String consumerName) {
this.consumeNum = consumeNum;
this.bc = bc;
this.setName(consumerName);
}
public void run() {
bc.consumeBread(consumeNum, this.getName());
}
}
public static void main(String[] args) {
Theaddemo thdo = new Theaddemo();
BreadContainer bc = thdo.new BreadContainer(60);
Producer p1 = thdo.new Producer(200, bc, "p1");
Producer p2 = thdo.new Producer(300, bc, "p2");
Producer p3 = thdo.new Producer(500, bc, "p3");
Consumer c1 = thdo.new Consumer(80, bc, "c1");
Consumer c2 = thdo.new Consumer(390, bc, "c3");
c1.start();
c2.start();
p1.start();
p2.start();
p3.start();
}
}