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

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章