java多线程六:多线程案例分析二-生产电脑

文章出处 https://www.jianshu.com/p/61882b068f6f

文章对应视频出处:https://developer.aliyun.com/course/1012?spm=5176.10731542.0.0.6ef2d290hxQ4g0

设计一个生产电脑和搬运电脑类,要求生产出一台电脑,就搬走一台电脑,如果没有新的电脑生产出来,则搬运工需要等待新电脑产出;如果生产出的电脑没有搬走,则要等待电脑搬走再生产,并统计处生产的电脑数。
  在本程序中,就是一个标准的生产者和消费者的处理模型,那么下面市县具体的程序代码。

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Resource res = new Resource();
        Producer st = new Producer(res);
        Consumer at = new Consumer(res);
        new Thread(at).start();
        new Thread(at).start();
        new Thread(st).start();
        new Thread(st).start();
    }
}
class Producer implements Runnable {
    private Resource resource;
    public Producer(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            try {
                this.resource.make();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Consumer implements Runnable {
    private Resource resource;
    public Consumer(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            try {
                this.resource.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Resource {
    private Computer computer;
    public synchronized void make() throws InterruptedException {
        while (computer != null) {//已经生产过了
            wait();
        }
        Thread.sleep(100);
        this.computer = new Computer("DELL", 1.1);
        System.out.println("【生产】" + this.computer);
        notifyAll();
    }
    public synchronized void get() throws InterruptedException {
        while (computer == null) {//已经生产过了
            wait();
        }
        Thread.sleep(10);
        System.out.println("【搬运】" + this.computer);
        this.computer = null;
        notifyAll();
    }
}
class Computer {
    private static int count;//表示生产的个数
    private String name;
    private double price;
    public Computer(String name, double price) {
        this.name = name;
        this.price = price;
        this.count++;
    }
    @Override
    public String toString() {
        return "【第" + count + "台电脑】电脑名字:" + this.name + "价值、" + this.price;
    }
}
发布了52 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/YKWNDY/article/details/104955497