MENU

生产电脑——多线程,标准的生产者与消费者模型

• November 21, 2020 • java高级特性

生产一个电脑,取走一个电脑,不能重复生产,不能重复取走,标准的生产者与消费者模型

class ProductComputer implements Runnable{
    private Resource resource;
    public ProductComputer(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        for (int i = 0; i < 25; i++) {
            this.resource.product();
        }
    }
}

class GetComputer implements Runnable{
    private Resource resource;
    public GetComputer(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        for (int i = 0; i < 25; i++) {
            this.resource.get();
        }
    }
}

class Computer{
    private String name;
    private double price;
    public Computer(String name, double price) {
        this.name = name;
        this.price = price;
    }
    public String getInfo(){
        return "电脑名称:" + this.name + " | 价格:" + this.price;
    }
}

class Resource{
    private int count = 0;
    private Computer computer;
    public synchronized void product(){
        if(this.computer != null){
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("正在生产电脑…………");
        this.computer = new Computer("MacBook",12999.99);
        this.count ++;
        super.notify();
    }
    
    public synchronized void get(){
        if(this.computer == null){
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 操作," + this.computer.getInfo());
        // 已经取走了
        this.computer = null;
        super.notify();
    }
    public int getCount() {
        return count;
    }
}

/**
 * @author Administrator
 */
public class Main {
    public static void main(String[] args) {
        Resource resource = new Resource();
        ProductComputer productComputer = new ProductComputer(resource);
        GetComputer getComputer = new GetComputer(resource);
        new Thread(productComputer, "生产").start();
        new Thread(getComputer, "取走").start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("共生产了 " + resource.getCount() + " 台电脑");
    }
}

代码编译器:IntelliJ IDEA 20.01

Archives QR Code Tip
QR Code for this page
Tipping QR Code