场景:
有若干只蜜蜂和若干只熊 一个蜜罐 每个蜜蜂有个袋子.
蜜蜂产蜜每次产一点用时10ms 熊每次吃光蜜罐中的蜂蜜
蜜罐的最大容量为30 袋子的最大容量为20
蜜蜂将每次的产的蜂蜜放在袋子里 当袋子中的蜂蜜大于5时就可以向 蜜罐添加蜂蜜
/**
* 蜜蜂 自带一个容量为5的囊 每次产1 耗时10ms,满足5的时候给蜜罐添加
*/
public class Bee extends Thread{
private int bag = 0;
private static final int BAG_MAX = 20;
private static final int ONCE = 5; //每生产5斤可以放入蜜罐
private static final int TIME = 10;//生产一斤花费10ms
private Box box;
private String name;
public Bee(String name, Box box){
this.name = name;
this.box = box;
}
public void run() {
while(true){
//如果不足5
if(bag >=0 && bag < 5){
bag++;
try {
Thread.sleep(10);
} catch (Exception e) {}
}
//满足放蜂蜜的条件
if(bag >= 5){
synchronized (box) {
//取出当前的蜜罐容量
int cap = box.capacity;
//蜜罐已满
if(cap >= Box.MAX){
box.notifyAll(); //通知熊吃蜜
}else{
//蜜罐剩余的空间
int remain = Box.MAX - cap;
//如果包中的量比罐中的多,就填满罐子
if(bag >= remain){
box.capacity = Box.MAX;
bag = bag - remain;
System.out.println(name+"添加了 = " +remain +" 蜜罐当前量:"+box.capacity);
box.notifyAll();
}
//不足remain
else{
box.capacity = box.capacity + bag;
System.out.println(name+"添加了 = " +bag +" 蜜罐当前量:"+box.capacity);
bag = 0;
}
}
}
}
//向小包增加蜂蜜,这部分代码不需要同步是并发完成的.
if(bag >= Bee.BAG_MAX){
synchronized (box) {
try {
box.wait();
} catch (Exception e) {}
}
}else{
bag ++;
System.out.println(name+"bag = "+bag);
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
}
/**
* 熊
*/
public class Bear extends Thread{
private Box box;
private String name;
public Bear(Box box,String name){
this.box = box;
this.name = name;
}
public void run() {
while(true){
synchronized (box) {
if(box.capacity == box.MAX){
int tmp = box.capacity;
box.capacity = 0;
System.out.println(name + ":" + "吃掉了" +tmp);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
box.notifyAll();
}else{
try {
box.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
/**
*蜜罐
*/
public class Box {
public static final int MAX = 30;
public int capacity = 0;
}
/**
* 蜜蜂的生产消费问题
*/
public class ThreadDemo3 {
public static void main(String[] args) {
Box box = new Box();
Bee bee1 = new Bee("b-1",box);
Bee bee2 = new Bee("b-2",box);
Bee bee3 = new Bee("b-3",box);
Bee bee4 = new Bee("b-4",box);
Bee bee5 = new Bee("b-5",box);
Bee bee6 = new Bee("b-6",box);
Bee bee7 = new Bee("b-6",box);
Bee bee8 = new Bee("b-6",box);
Bee bee9 = new Bee("b-6",box);
Bee bee10 = new Bee("b-6",box);
Bear bear1 = new Bear(box,"熊大");
//Bear bear2 = new Bear(box,"熊二");
bee1.start();
bee2.start();
bee3.start();
bee4.start();
bee5.start();
bee6.start();
bee7.start();
bee8.start();
bee9.start();
bee10.start();
bear1.start();
//bear2.start();
}