import java.util.ArrayList;
import java.util.List;
/*
4个生产者随机生产n个面包,要求每人每次最多不能超过40个,而且总共最多不能生产超过100个,
同时,有5个消费者随机消费这些面包,每人每次不能消费超过30个。
要求打印以下信息:
例如: 生产者XX 生产 6个面包
消费者XX 消费4个面包
如果满了,则打印: 已经达到100个了!请停止生产..
如果空了,则打印: 已经吃空了!请速度生产...*/
public class Bakery {// 面包房存放面包
Bread bread;// 有面包
List<Bread> list = new ArrayList<Bread>();// 有一个list里面可以放很多面包
int holdermax = 100;// 共可以放的数量 最多不能超过100个
int count = 0;
public List<Bread> getList() {
return list;
}
/*
* public void setList(List<Bread> list) { this.list = list; }
*
* /** 放list里面加面包的方法
*
* @throws InterruptedException
*/
public synchronized void push(Bread bread) throws InterruptedException {// 得到一个面包
// 判断加满的时候
if (list.size() >= holdermax) {
wait();// 等待,太多了,不能再放面包了
System.out.println("已有" + (list.size() + 1) + "个,已放满,请等待");
return;// 没有加return会一直走判断流程
}
list.add(bread);// 加面包
notify();// 动作已做完,通知另一个线程
}
/**
* 放list里面取 面包的方法
*
* @throws InterruptedException
*/
public synchronized void down() throws InterruptedException {
// 判断取空的时候
if (list.size() <= 0) {// 不于1个的时候,进入if等待
wait();
System.out.println("剩余" + list.size() + "个,不多了,请等待");
return;
}
list.remove(0);// 减去list里面的面包数
notify();// 动作已做完,通知另一个线程
}
/**
* 返回一个0-100的随机数
*
* @return
*/
public int addRandon() {
int b = 0;
float a = (float) Math.random() * 100;// 产生一个0-1之间的数,再*100
if(a==0){
addRandon();//不能让这个数等于0
}
return b = (int) a;// 去掉小数点后面的数
}
}
//消费者
public class Consumer implements Runnable {
// 有一个Bakery
Bakery bakery;
public Consumer(Bakery bakery) {
super();
this.bakery = bakery;
}
public void reduce() {
int b = 0;
while (true) {
try {
for (int i = 0; i < bakery.addRandon(); i++) {
if (i > 30) {
notify();
return;
} else {
bakery.down();
b = i;
}
}
System.out.println(Thread.currentThread().getName() + "消费了" + b + "个面包");
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
reduce();
}
}
//生产者----------------------------------------------------
package 生产者与消费者2;
public class Producer implements Runnable {
// 有一个Bakery
Bakery bakery;
public Producer(Bakery bakery) {
super();
this.bakery = bakery;
}
public void add() {
int b = 0;
while (true) {// 加上while,让他无限循环,要不然到最大数量后,就会自动停止
Bread bread = new Bread();
try {
for (int i = 0; i < bakery.addRandon(); i++) {// 循环多少次,等于生产多少次
if (i > 40) {
notify();
return;
} else {
bakery.push(bread);// 调用方法,加一个面包进去
b = i;
}
}
System.out.println(Thread.currentThread().getName() + "生产" + b + "个面包");
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
add();
}
}
--------------------------------------------
public class Bread {
}