package com.huang;
/**
* @author huangwentao
* @since 2021/11/12 21:55
*/
public class TestBuy {
public static void main(String[] args) {
Store store = new Store(10);
new Worker(store).start();
new Worker(store).start();
new Customer(store).start();
new Customer(store).start();
}
}
/**
* 商品类
*/
class Good {
private final String name;
Good(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
/**
* 仓库类
*/
class Store {
private final Good[] goods;
private final int max;
private int count = 0;
public Store(int max) {
this.max = max;
goods = new Good[max];
}
public synchronized void pushGood(Good good) throws InterruptedException {
// 仓库满了,等待,这里要使用while,否则可能产生虚假唤醒
while (count == max)
this.wait();
goods[this.count++] = good;
if (count != 0)
this.notifyAll();
System.out.println("生产了 " + good.getName() +
" 仓库产品数" + this.count);
}
public synchronized Good getGood() throws InterruptedException {
Good good;
while (count == 0)
this.wait();
good = goods[--this.count];
// 仓库未满,通知生产者生产
if (count < max)
this.notifyAll();
System.out.println("购买了 " + good.getName() +
" 仓库产品数" + this.count);
return good;
}
}
/**
* 生产者
*/
class Worker extends Thread {
private final Store store;
public Worker(Store store) {
this.store = store;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
store.pushGood(new Good("商品" + Thread.currentThread().getName() + "-" + i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 消费者
*/
class Customer extends Thread {
private final Store store;
public Customer(Store store) {
this.store = store;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Good good = store.getGood();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}