题目:设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果没有新的电脑生产出来,则搬运工要等待新电脑产出,如果生产出的电脑没有搬走,则要等待电脑搬走之后再生产,并统计出生产的电脑数量。
在本程序之中实现的就是一个标准的生产者与消费者的处理模型
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();
}
}