public class Producers_Consumers {
public static void main(String[] args) {
//共同资源
Food food = new Food();
//多线程
Producers p = new Producers(food);
Consumers c = new Consumers(food);
new Thread(p).start();
new Thread(c).start();
}
}
class Food{
private String food;
/*
* flag=true --> 生产者生产,消费者等待,通知消费者消费
* flag=false --> 消费者消费,生产者等待,通知生产者生产
*/
private boolean flag = true;
public synchronized void making(String food){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始生产
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产者生产了"+food);
//生产完毕
this.food = food;
//唤醒消费者
this.notifyAll();
//生产者停下
this.flag = false;
}
public synchronized void eating(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始生产
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者消费了"+food);
//消费完毕,唤醒生产者
this.notifyAll();
//消费停止
this.flag = true;
}
}
class Producers implements Runnable{
private Food food;
public Producers(Food food){
this.food = food;
}
public void run() {
for(int i=0; i<20; i++){
if(i%2 == 0){
food.making("糖醋排骨"+i);
}else{
food.making("红烧猪蹄"+i);
}
}
}
}
class Consumers implements Runnable{
private Food food;
public Consumers(Food food){
this.food = food;
}
public void run() {
for(int i=0; i<20; i++){
food.eating();
}
}
}