多线程小猪佩奇吃煎饼
猪妈妈为小猪佩琪和弟弟乔治准备午餐。猪妈妈将煎好的煎饼放在一个盘子里,盘子里面只能放一块煎饼。猪妈妈煎好一块煎饼需要3s,佩琪吃掉一块煎饼需要5s,乔治吃掉一块煎饼需要4s。假设猪妈妈总共煎了n块煎饼。请你编程模拟它们这个过程。1、盘子里面只能放一块煎饼。如果盘子里还有煎饼,则煎饼不能放进去。2、佩琪和乔治只能在盘子中有煎饼时才能取得煎饼,同时必须吃完了手上的煎饼才能去取盘子里的煎饼。3、最后统计一下佩琪和乔治各吃了几块煎饼。
这个小猪佩奇和乔治是个猪!!!
package main;
public class Main {
static int Count = 20;
static int n = 1;
public static void main(String[] args) {
Food food = new Food();
PigMother pm = new PigMother(food);
PeppaPig pp = new PeppaPig(food);
George george = new George(food);
Thread p = new Thread(pm);
Thread pe = new Thread(pp, "佩琪");
Thread g = new Thread(george, "乔治");
p.start();
pe.start();
g.start();
}
}
class Food {
private String name;
private boolean flog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Food() {
super();
this.flog = false;
}
public Food(String name) {
this.name = name;
this.flog = false;
}
public synchronized void set(String name) {
if (flog) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("猪妈妈正在煎第" + (Main.n) + "块煎饼");
this.setName(name);
flog = true;
super.notifyAll();
}
public synchronized void get() {
if (!flog) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("第" + (Main.n++) + "块" + toString() + "正在被" + Thread.currentThread().getName() + "吃");
flog = false;
super.notifyAll();
}
public String toString() {
return this.name;
}
}
class PigMother implements Runnable {
private Food food;
public PigMother() {
super();
}
public PigMother(Food food) {
this.food = food;
}
public Food getFood() {
return food;
}
public void setFood(Food food) {
this.food = food;
}
@Override
public void run() {
while (Main.Count > 0) {
makeBattercake();
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private synchronized void makeBattercake() {
if (Main.Count > 0) {
food.set("猪煎饼");
Main.Count--;
}
}
}
class PeppaPig implements Runnable {
private Food food;
private int count;
public PeppaPig() {
super();
}
public PeppaPig(Food food) {
this.food = food;
this.count = 0;
}
@Override
public void run() {
while (Main.Count > 0) {
food.get();
count++;
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("佩琪一共吃了" + count + "块煎饼");
}
}
class George implements Runnable {
private Food food;
private int count;
public George() {
super();
}
public George(Food food) {
this.food = food;
this.count = 0;
}
@Override
public void run() {
while (Main.Count > 0) {
food.get();
count++;
try {
Thread.sleep(4000);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("乔治一共吃了" + count + "块煎饼");
}
}