奶箱:相当于缓冲区,容量有限,生产者放入牛奶,消费者拿走牛奶
生产者:实现 Runnable 接口,箱子内有牛奶就取出,没有就等着
消费者:实现 Runnable 接口,箱子还有剩余空间就往里放牛奶,箱子满了就等着
奶箱类
public class Box {
private int count = 0; //当前奶箱内奶瓶数量
private int max = 5; //奶箱大小
public synchronized void put(int milk) { //想放milk瓶牛奶
System.out.println("想放" + milk);
if (count == max) { //奶箱已满,放不了,等人取
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count + milk > max) { //箱内数量+想放数量 > 箱子容量,能放几瓶就放几瓶
System.out.println("放入" + (max - count));
count = max;
} else { //想放数量 > 剩余容量
this.count += milk;
System.out.println("放入" + milk);
}
System.out.println("还剩余" + count);
notifyAll();
}
public synchronized void get(int milk) { //想取milk瓶牛奶
System.out.println("想取" + milk);
if (count == 0) { //箱子内无牛奶,只能等
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (milk > count) { //想取的数量 > 箱子内数量,能拿几瓶拿几瓶
count = 0;
System.out.println("取出" + count);
} else { //箱子内数量 > 想取的数量
count -= milk;
System.out.println("取出" + milk);
}
System.out.println("还剩余" + count);
notifyAll();
}
}
生产者(送奶工)
public class Producer implements Runnable { //送奶工
private Box b = null;
public Producer(Box b) {
this.b = b;
}
@Override
public void run() {
while (true) {
//随机生成想放的数量
Random random = new Random();
b.put(random.nextInt(5) + 1);
//休息一下
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者
public class Costomer implements Runnable { //消费者
private Box b = null;
public Costomer(Box b) {
this.b = b;
}
@Override
public void run() {
while (true) {
//随机生成想取的梳理
Random random = new Random();
b.get(random.nextInt(5) + 1);
//休息一下
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类
public class BoxTest {
public static void main(String[] args) {
Box b = new Box();
Producer p = new Producer(b);
Costomer c = new Costomer(b);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}