线程通信_生产消费4S店案例
经典 生产消费者面试题 (wait、notify 实现)
4S店存放生产的汽车
生产者线程生产汽车
消费者线程购买汽车
4S店最多只能存放4台车,如果达到4台车生产者停止生产
如果4S店没有库存车,消费需等待有库存后,方可购买
import java.util.LinkedList;
public class D2_线程通信_生产消费4S店案例 {
static final int CAR_STORE_NUM = 4;
static int CAR_NUM = 1;
public static void main(String[] args) {
Car4s car4S = new Car4s();
Thread product1 = new Thread(new ProductCar(car4S));
Thread consumer1 = new Thread(new ConsumerCar(car4S));
product1.start();
consumer1.start();
}
static class ProductCar implements Runnable {
Car4s car4s;
public ProductCar(Car4s car4s) {
this.car4s = car4s;
}
@Override
public void run() {
while (true) {
synchronized (car4s) {
if (car4s.cars.size() >= CAR_STORE_NUM) {
System.out.println("当前库存已满,生产者休息");
try {
car4s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Car car = new Car();
car.setName(CAR_NUM + "");
car4s.cars.push(car);
System.out.println("生产汽车==>" + car.getName());
CAR_NUM++;
car4s.notify();
}
}
}
}
}
static class ConsumerCar implements Runnable {
Car4s car4s;
public ConsumerCar(Car4s car4s) {
this.car4s = car4s;
}
@Override
public void run() {
while (true) {
synchronized (car4s) {
if (car4s.cars.size() <= 0) {
System.out.println("当前4S店无库存,消费者休息");
try {
car4s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Car poll = car4s.cars.poll();
System.out.println("购买到汽车 ==>" + poll.getName());
car4s.notify();
}
}
}
}
}
static class Car4s {
LinkedList<Car> cars = new LinkedList<>();
}
static class Car {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}