《JAVA开发实战经典》P311练习

//设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果没有新的电脑生产出来,
// 则搬运工要等待新电脑产出;如果生产出的电脑没有搬走,则要等待电脑搬走后再生产,
// 并统计出生产的电脑数量
import java.rmi.server.ExportException;
import java.util.TreeMap;
class Computer{
    private String mold = "Computer";
    private String name;
    private int count = 1;                              //用来统计生产的数量
    private boolean flag = true;
    public synchronized void setName(){
        if (!flag){
            try{
                super.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        name = mold + count;
        count++;

        flag = false;
        super.notify();
    }
    public synchronized void getName(){
        if (flag){
            try{
                super.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }

        System.out.println(this.name);
        flag = true;
        super.notify();
    }
}

class Producer implements Runnable{
    Computer com = null;
    public Producer(Computer com){
        this.com = com;
    }
    public void run(){
        for (int i = 0;i < 10;i++){
            com.setName();
        }
    }
}

class Consumer implements Runnable{
    Computer com = null;
    public Consumer(Computer com){
        this.com = com;
    }
    public void run(){
        for (int i = 0;i < 10;i++){
            com.getName();
        }
    }
}
public class Main{
    public static void main(String[] args) {
        Computer c = new Computer();
        Producer pro = new Producer(c);
        Consumer con = new Consumer(c);
        new Thread(pro).start();
        new Thread(con).start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值