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

该博客展示了如何使用Java实现一个经典的生产者消费者问题。通过`Coumputer`类表示电脑产品,`Resource2`类作为共享资源,包含生产和获取电脑的方法。`Producer`和`Consumer`类分别代表生产者和消费者线程,它们通过`synchronized`关键字和`wait()`、`notifyAll()`方法协调工作,确保生产与消费的同步。程序运行过程中,生产者线程生成电脑并通知消费者线程取走,消费者线程在电脑可用时取走并通知生产者可以继续生产,从而达到同步效果。
4790

被折叠的 条评论
为什么被折叠?



