public class ConsumerAndProducer{
public static void main(String[] args){
Box box=new Box();
Producer p=new Producer(box);
Consumer c=new Consumer(box);
new Thread(p).start();
new Thread(c).start();
}
}
class Food{
int id;
Food(int id){
this.id=id;
}
public String toString(){
return "Food : " + this.id;
}
}
class Box{
int index = 0;
Food[] arrFood = new Food[6];
public synchronized void put(Food food){
while(index==arrFood.length){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notifyAll();
arrFood[index++]=food;
}
public synchronized Food get(){
while(index==0){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notifyAll();
return arrFood[--index];
}
}
class Producer implements Runnable{
Box box=null;
Producer(Box box){
this.box=box;
}
public void run(){
for(int i=0;i<20;i++){
Food food = new Food(i);
System.out.println("Put : " + food);
box.put(food);
try{
Thread.sleep((int)(Math.random()*100));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
Box box=null;
Consumer(Box box){
this.box=box;
}
public void run(){
for(int i=0;i<20;i++){
Food food=box.get();
System.out.println("Get : " + food);
try{
Thread.sleep((int)(Math.random()*200));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}