用JAVA实现一个关系

来源:百度知道 编辑:UC知道 时间:2024/06/16 05:44:38
生产者,消费者和仓库的关系:

生产者 生产 物品 存入仓库

消费者 去 仓库 取出

用java 实现这个关系。

下面是模版,不能运行:
share data

#define BUFFER_SIZE 10
Typedef struct

。。。。
}item;
item buffer[BUFFER_SIZE];
int in =0;
int out =0;

item nextproduced

whicle (1)

whicle(((in+1)%BOFFER_SIZE==out);/*do nothing*/
buffer[in]=next preduced;
in=(in+1)%BUFFER_SIZE;


item nextconsumed

whicle(1)
{
whicle(in==out);/*do nothing*/
next consumed=buffer[out];
out=(out+1)%BUFFER_SIZE;

}
谢谢zhaohaic01的回答,小改下就正确了。

//生产者
public class Producer extends Thread{
private CubbyHole cubbyhole;
private int number;

public Producer(CubbyHole c,int number){
cubbyhole=c;
this.number=number;
}

public void run(){
for(int i=0;i<10;i++){
cubbyhole.put(i);
System.out.println("Producer #"+this.number+"put:"+i);
try{sleep((int)(Math.random()*100));}catch(InterruptedException e){}
}
}
}
//消费者
public class Consumer extends Thread{
private CubbyHole cubbyhole;
private int number;

public Consumer(CubbyHole c,int number){
cubbyhole=c;
this.number=number;
}

public void run(){
int value=0;
for(int i=0;i<10;i++){
value=cubbyhole.get();
System.out.println("Consumer#"+this.number+"got:"+value);
}
}

}
//仓库
public class CubbyHole {
private int s