package work8;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
class Food{
private String name="";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Food(String name) {
this.name=name;
}
}
class WorkRoom{
static final int Maxstore=5;
List store=new ArrayList();
private int getFoodStoreAmount(String name) {
if(store==null || store.size()==0) return 0;
int count=0;
Iterator iterator=store.iterator();
while(iterator.hasNext()) {
if(iterator.next().getName().equals(name)) count++;
}
return count;
}private int getFoodIndex(String name){
if(store==null||store.size()==0) return -1;
for(int i=0;i<store.size();i++)
if(store.get(i).getName().equals(name)) return i;
return -1;
}
public void produce(String foodName) {
synchronized(store) {
int foodCount=getFoodStoreAmount(foodName);
if(foodCount>=WorkRoom.Maxstore) {
System.out.println("【"+foodName+"】的库存量【"+foodCount+"】件,最高库存!");
store.notifyAll();
try {
store.wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}else {
Food food=new Food(foodName);
store.add(food);
store.notifyAll();
System.out.println("【"+foodName+"】已生产,目前库存量【"+(foodCount+1)+"】件!");
}
}
}
public void cosume(String foodName) {
synchronized(store){
int foodIndex=getFoodIndex(foodName);
if(foodIndex<0) {
System.out.println("【"+foodName+"】的库存量【0】件,需要生产!");
store.notifyAll();
try {
store.wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}else {
Food food=store.get(foodIndex);
System.out.println("卖出一份【"+foodName+"】的食物!");
store.remove(food);
store.notifyAll();
}
}
}
}
class Producer implements Runnable{
private WorkRoom workRoom=null;
public Producer(WorkRoom room) {
this.workRoom=room;
}
@Override
public void run() {
while(true) {
Random rand=new Random();
int randIndex=rand.nextInt(4);
if(randIndex==1) workRoom.produce("鸡腿");
if(randIndex==2) workRoom.produce("薯条");
if(randIndex==3) workRoom.produce("可乐");
try {
Thread.sleep(10000);
}catch(InterruptedException e) {
e.printStackTrace();
System.out.println("程序生产中断!");
}
}
}
}
class Customer implements Runnable{
private WorkRoom workRoom=null;
public Customer(WorkRoom room) {
this.workRoom=room;
}
@Override
public void run() {
while(true) {
Random rand=new Random();
int randIndex=rand.nextInt(4);
if(randIndex==1) workRoom.cosume("鸡腿");
if(randIndex==2) workRoom.cosume("薯条");
if(randIndex==3) workRoom.cosume("可乐");
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
System.out.println("程序生产中断!");
}
}
}
}
public class runMain {
public static void main(String[] args) {
WorkRoom room=new WorkRoom();
Customer cust=new Customer(room);//这里为什么要带参数,为什么不带参数他就报错?
Producer pro=new Producer(room);
Thread tCustomer=new Thread(cust);
tCustomer.start();
Thread tProducer=new Thread(pro);
tProducer.start();
}
}
怎么办,他一直在运行怎么办?他停不下来了