线程之生产汽车与购买汽车

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();
        }
    }

}
原文地址:https://www.cnblogs.com/yugeng/p/7875769.html