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();
            }
        }
    
    }
  • 相关阅读:
    学习:Intents和Intent Filters(理论部分)
    天书夜读:从汇编语言到Windows内核编程笔记(1)
    学习:Intents和Intent Filters(实例部分)
    寒江独钓(1):内核数据类型和函数
    寒江独钓(2):串口的过滤
    学习:了解WDK目录
    Nginx 414 RequestURI Too Large 海口
    Ansible 批量修改密码 海口
    记一次node进程无法kill 问题 海口
    Vue学习心得新手如何学习Vue(转载)
  • 原文地址:https://www.cnblogs.com/yugeng/p/7875769.html
Copyright © 2011-2022 走看看