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();
            }
        }
    
    }
  • 相关阅读:
    start tag, end tag issues in IE7, particularly in xslt transformation
    用SandCastle为注释生成chm文档
    Firebug
    架构的重点
    Linux Shell常用技巧(十) 管道组合
    Linux JDK升级
    Linux Shell常用技巧(十二) Shell编程
    Packet Tracer 5.0实验(一) 交换机的基本配置与管理
    Linux Shell常用技巧(六) sort uniq tar split
    Linux Shell常用技巧(二) grep
  • 原文地址:https://www.cnblogs.com/yugeng/p/7875769.html
Copyright © 2011-2022 走看看