您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页多线程案例分析二:生产电脑

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

来源:二三娱乐

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

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);
         = new Computer("DELL", 1.1);
        System.out.println("【生产】" + 
        notifyAll();
    }
    public synchronized void get() throws InterruptedException {
        while (computer == null) {//已经生产过了
            wait();
        }
        Thread.sleep(10);
        System.out.println("【搬运】" + 
         = 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;
    }
}

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务