使用安全锁,实现送奶和取奶功能
1-奶箱类,包含需要送牛奶的数量,和奶箱是否为空的状态
package advanced.nine.ninethree;
/**
* @author Object(object_hui@sina.com)
* @description 一个奶箱,多线程的使用案例
* @date 2020/9/13
*/
public class Box{
//表示需要送多少瓶奶
private int milk;
//false表示奶箱没有奶
private boolean bool = false;
public Box() {
}
public Box(int milk, boolean bool) {
this.milk = milk;
this.bool = bool;
}
//往奶箱放奶
public synchronized void input(int milk){
//如果奶箱中有牛奶,就等着
if(bool){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//否则就生产牛奶
this.milk=milk;
//将牛奶放入奶箱
System.out.println(Thread.currentThread().getName()+"将弟 "+this.milk+" 瓶牛奶放入了奶箱!~");
//将奶箱状态置换为真
bool = true;
//唤醒等待线程
notifyAll();
}
//从奶箱取奶
public synchronized void output(){
//如果奶箱中没有奶就等着
if(!bool){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}//否则就取奶
System.out.println(Thread.currentThread().getName()+"将弟 "+this.milk+" 瓶牛奶取出了奶箱!~");
//奶箱状态为false
bool = false;
//唤醒等待线程
notifyAll();
}
}
2-生产者,实现了多线程方法
package advanced.nine.ninethree;
/**
* @author Object(object_hui@sina.com)
* @description 牛奶生产者类
* @date 2020/9/13
*/
public class Producer implements Runnable{
private Box b;
public Producer() {
}
public Producer(Box b) {
this.b = b;
}
public Box getB() {
return b;
}
public void setB(Box b) {
this.b = b;
}
@Override
public void run() {
for (int i = 1; i <= 7; i++) {
b.input(i);
}
}
}
3-消费者,实现了多线程方法
package advanced.nine.ninethree;
/**
* @author Object(object_hui@sina.com)
* @description 牛奶消费者
* @date 2020/9/13
*/
public class Customer implements Runnable {
private Box b;
public Customer() {
}
public Customer(Box b) {
this.b = b;
}
@Override
public void run() {
while (true){
b.output();
}
}
}
4-测试类
package advanced.nine.ninethree;
/**
* @author Object(object_hui@sina.com)
* @description 奶箱测试类
* @date 2020/9/13
*/
public class Demo01 {
public static void main(String[] args) {
Box box = new Box();
Producer po = new Producer(box);
Customer co = new Customer(box);
Thread td1 = new Thread(po,"送奶工");
Thread td2 = new Thread(co,"用户");
td1.start();
td2.start();
}
}
5-执行结果
Thread td1 = new Thread(po,"送奶工");
Thread td2 = new Thread(co,"用户");
td1.start();
td2.start();
}
}
#### 5-执行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200914000537782.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ppYW84OTAxMjI=,size_16,color_FFFFFF,t_70#pic_center)