多线程-生产电脑

题目:设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果没有新的电脑生产出来,则搬运工要等待新电脑产出,如果生产出的电脑没有搬走,则要等待电脑搬走之后再生产,并统计出生产的电脑数量。

在本程序之中实现的就是一个标准的生产者与消费者的处理模型

package Thread;

class Coumputer{
    private static int count = 0; //表示生产个数
    private String name;
    private double price;
    public Coumputer(String name,Double price){
        this.name = name;
        this.price = price;
        count ++;
    }
    public String toString(){
        return "[第"+ count + "台电脑]" + "电脑名字:" + this.name + ",价值:" + this.price;
    }
}


class Resource2{
    private Coumputer coumputer;
    public synchronized void make() throws Exception{
        if(this.coumputer != null){	//生成过了
            super.wait();
        }
        Thread.sleep(100);
        this.coumputer = new Coumputer("拯救者笔记本电脑",6499.99);
        System.out.println("[生产电脑]"+this.coumputer);
        super.notifyAll();
    }
    public synchronized void get() throws Exception{
        if(this.coumputer == null){	//还没生成
            super.wait();
        }
        Thread.sleep(10);
        System.out.println("[取走电脑]"+this.coumputer);
        this.coumputer = null;
        super.notifyAll();
    }

}


class Producer implements Runnable{
    private Resource2 resource;
    public Producer(Resource2 resource){
        this.resource = resource;
    }
    public void run(){
        for(int x=0;x<50;x++){
            try {
                this.resource.make();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
class Consumer implements Runnable{
    private Resource2 resource;
    public Consumer(Resource2 resource){
        this.resource = resource;
    }
    public void run(){
        for(int x=0;x<50;x++){
            try {
                this.resource.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


public class CoupuertThread {
    public static void main(String[] args) throws Exception{
        Resource2 res = new Resource2();
        new Thread(new Producer(res)).start();
        new Thread(new Consumer(res)).start();
    }
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值