java生产者消费者问题



java生产者消费者问题。public class Test {
public static void main(String[] args) {

Basket basket = new Basket();
Create create = new
Create(basket);
Eat eat = new Eat(basket);
Thread threadC = new Thread(create);
Thread threadE = new Thread(eat);

threadC.start();
threadE.start();
}
}

public class
Basket {
// 设置篮子的大小为10个
WoTou[] woTous = new WoTou[10];

int index = 0;

public synchronized void put(WoTou woTou) {

if (index == woTous.length) {
try {

this.wait();
} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();
}
}

this.notify();
woTous[index] = woTou;
index++;

System.out.println(“生产了窝头”+index);

}

public synchronized
int get() {
if (index == 0) {
try {

this.wait();
} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();
}
}


this.notify();
index–;
//        woTous[index] = null;
//
System.out.println(“吃掉了窝头” + index+1);
return index;

}
}

public class Create implements Runnable {
Basket
basket;

public Create(Basket basket) {
this.basket =
basket;
}

public void run() {
// TODO
Auto-generated method stub
for (int i = 0; true; i++) {

WoTou woTou = new WoTou(i);
basket.put(woTou);

}
}

}

public class Eat implements Runnable {
Basket
basket;

public Eat(Basket basket) {
this.basket =
basket;
}

public void run() {
// TODO
Auto-generated method stub
int index = 0;
for (int i = 0;
true; i++) {
index = basket.get();

basket.woTous[index] = null;
System.out.println(“吃掉了窝头” + (index
+ 1));
}
}

}

public class WoTou{
public
WoTou(int id){
this.id = id;
}

int id ;

public int getId() {
return id;
}
public void
setId(int id) {
this.id = id;
}

}