生产者消费者模式是一个十分经典的多线程协作的模式,弄懂生产者消费者问题能够让我们对多线程编程的理解更加深刻。
// Main.java
Box b = new Box();
Producer p = new Producer(b); // 生产者
Customer c = new Customer(b); // 消费者
Thread th1 = new Thread(p);
Thread th2 = new Thread(c);
th1.start();
th2.start();
// Producer.java
public class Producer implements Runnable{
private Box b;
public Producer(Box b){
this.b = b;
}
@Override
public void run() {
for(int i = 0; i < 30;i++){
b.put(i);
}
}
}
// Customer.java
public class Customer implements Runnable{
private Box b;
public Customer(Box b){
this.b = b;
}
@Override
public void run() {
while(true){
b.get();
}
}
}
// Box.java
public class Box {
private int milk;
private boolean state = false; // 有无奶的状态
// producer 在跑这个线程
public synchronized void put(int milk){
if(state){ // 有奶 就进行等待,等消费者消费
try{
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
this.milk = milk;
System.out.println("送奶工将第" + this.milk + "瓶奶放入奶箱");
state = true;
// notifyAll();
}
// Customer 在跑这个线程
public synchronized void get(){
if(!state){ // 无奶 就进行等待,等生产者生产
try{
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println("用户拿到第" + this.milk + "瓶奶");
state = false;
// notifyAll();
}
}