用多线程的生产者消费者模式实现工厂的面包运到超市,顾客去超市购买,超市每次最大存储6个面包。
public class Test1Consumer {
public static void main(String[] args) {
Supermarkt s = new Supermarkt();
Factory f = new Factory(s);
Consumer c = new Consumer(s);
Thread t = new Thread(f, "工厂");
Thread t1 = new Thread(c, "顾客");
t.start();
t1.start();
}
}
class Brand {
int id;
String name;
public Brand(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Supermarkt {
Brand b[] = new Brand[6];
int index = -1;
// 运面包
public synchronized void addBrand(Brand brand) throws InterruptedException {
if (index >= 5) {
this.wait();
}
index++;
b[index] = brand;
System.out.println(Thread.currentThread().getName() + "卖了"
+ brand.getId() + "个" + brand.getName() + "的面包,超市一共还有"
+ (index + 1) + "个");
this.notifyAll();
}
// 卖面包
public synchronized void saleBrand() throws InterruptedException {
if (index <= -1) {
this.wait();
}
// 打印卖出去面包的信息
System.out.println(Thread.currentThread().getName() + "买掉了"
+ b[index].getId() + "个" + b[index].getName() + "的面包,超市还剩下"
+ (index) + "个");
index--;
this.notifyAll();
}
}
class Factory implements Runnable {
Supermarkt markt;
public Factory(Supermarkt markt) {
super();
this.markt = markt;
}
@Override
public void run() {
for (int i = 0; i < 80; i++) {
try {
markt.addBrand(new Brand(1, "难吃"));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
Supermarkt sup;
public Consumer(Supermarkt sup) {
super();
this.sup = sup;
}
@Override
public void run() {
for (int i = 0; i < 80; i++) {
try {
sup.saleBrand();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}