zoukankan      html  css  js  c++  java
  • 线程之生产汽车与购买汽车

    package Thread1;
    
    /**
     * 主方法
     * 
     * @author zhangyugeng 
     * 创建汽车类Car 创建汽车工厂类CarFactory 创建顾客类Client
     */
    
    public class CreateAndBuyCar {
    
        public static void main(String[] args) {
            Car car = new Car();
            CarFactory factory = new CarFactory(car);
            Client client = new Client(car);
            new Thread(factory).start();
            new Thread(client).start();
    
        }
    
    }
    
    /**
     * @author zhangyugeng 
     * 汽车类
     */
    class Car {
        boolean existCar = false; // 判断是否存在汽车
        /* 创造汽车的方法 */
    
        public synchronized void createCar() throws InterruptedException {
            if (existCar) {
                wait(); // 存在汽车就等候
    
            }
            System.out.println("库存没有汽车,正在生产汽车");
            Thread.sleep(6000); // 模拟生产车的时间
            System.out.println("生产了大众汽车");
            notifyAll(); // 唤醒其他线程,让顾客知道可以买车了
            existCar = true;
    
        }
    
        /* 购买汽车的方法 */
        public synchronized void buyCar() throws InterruptedException {
            if (!existCar) {
                wait(); // 不存在汽车,顾客就等候买车
            }
            System.out.println("正在购买汽车");
            Thread.sleep(2000); // 模拟购买汽车时间
            System.out.println("买好了大众汽车");
            System.out.println();
            Thread.sleep(1000);
            notifyAll();
            existCar = false;
    
        }
    
    }
    
    /**
     * 汽车工厂类
     */
    class CarFactory implements Runnable {
        Car car;
    
        public CarFactory(Car car) {
    
            this.car = car;
        }
    
        @Override
        public void run() {
    
            try {
                for (int i = 0; i < 3; i++)
                    car.createCar(); // 生产车
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    }
    
    /**
     * 顾客类
     */
    class Client implements Runnable {
    
        Car car;
    
        public Client(Car car) {
    
            this.car = car;
        }
    
        @Override
        public void run() {
    
            try {
                for (int i = 0; i < 3; i++)
                    car.buyCar(); // 购买车
            } catch (InterruptedException e) {
    
                e.printStackTrace();
            }
        }
    
    }
  • 相关阅读:
    vue跨域请求图片 返回前端代码无法加载图片
    神奇的选择器 :focus-within
    vue.js实现div展开收起动画
    vue+element 点击页面内跳转按钮 导航菜单选中
    css实现文本两端对齐最后一行左对齐
    鼠标拖动图片,禁止在新窗口中打开图片
    Java获取application.properties配置参数
    css处理文字不换行、换行截断、溢出省略号
    java获取当前服务器地址 例 http://localhost:xxxx
    web负载均衡
  • 原文地址:https://www.cnblogs.com/yugeng/p/7875769.html
Copyright © 2011-2022 走看看