线程通信_生产消费4S店案例

线程通信_生产消费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;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值