class Box{
private int milk;
private boolean state=false;
public synchronized void put(int milk) {//同步代码块:执行这块代码后,所在线程加锁,不会被抢占使用权。
//这时其他线程要执行,需要wait()该线程,notify()其他线程
if(state) { //有奶,不再继续放,put的线程暂停,等待get线程拿出奶
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//state=false,没有奶,生产者放入奶,这是第i瓶
this.milk=milk;
System.out.println("生产者放入第"+this.milk+"瓶奶");
state=true; //有了奶,奶箱不为空,修改奶箱状态
notifyAll(); //唤醒其他所有线程(唤醒get线程,取出牛奶)
}
public synchronized void get() {
if(!state) { //state=false,没有奶,消费者没法拿出奶,只能等待
try {
wait(); //消费者的get行为/线程开始等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//state=true,有奶,可以拿出,这是第i瓶奶
System.out.println("消费者拿出第"+this.milk+"瓶奶");
state=false; //拿出以后,box空,修改box状态
notifyAll(); //唤醒其他所有线程(唤醒put线程,开始放入)
}
}
class Producer implements Runnable{
private Box b;
public Producer(Box b) {
this.b=b;
}
@Override
public void run() {
for(int i=1;i<11;i++) {
b.put(i);
}
}
}
class Customer implements Runnable{
private Box b;
public Customer(Box b) {
this.b=b;
}
@Override
public void run() {
while(true) {
b.get();
}
}
}
public class Milk {
public static void main(String[] args) {
Box b=new Box(); //创建一个奶箱
Producer p=new Producer(b); //都用这个奶箱
Customer c=new Customer(b);
Thread t1=new Thread(p); //producer在线程1中
Thread t2=new Thread(c); //customer在线程2中
t1.start();
t2.start();
}
}
案例:生产者每天生产一瓶奶,放入奶箱,消费者拿出奶后,生产者再生产,放入
思路:四个类
1.Box:奶箱
2.Producer:生产者,实现Runnable接口,put()存放操作
3.Customer:消费者,实现Runnable接口,get()取出操作
4.Demo:主类,main,创建Box、producer、customer、Thread,开启线程