多线程实现,生产者和消费者吃蛋糕问题。我认为问题出在类cake上,但是不会改,希望大神能给予帮助,谢谢
package duoxiancheng;
public class cake {
private int id;
public cake(){
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public class basket {
private cake[] cakes=new cake[10];
private int currentIndex=0;
public synchronized void push(cake cake){
while(currentIndex >= cakes.length){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
cakes[currentIndex]=cake;
currentIndex++;
System.out.println("放入:"+cake.toString());
notify();
}
public synchronized cake pop(){
while(currentIndex <= 0){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
currentIndex--;
cake temp=cakes[currentIndex];
System.out.println("吃掉:"+temp.toString());
notify();
return temp;
}
}
public class productor extends Thread {
private basket basket;
public productor(basket basket){
this.basket=basket;
}
public void run(){
while(true){
basket.pop();
//System.out.println("放入:"+cake.toString());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class customer implements Runnable{
private basket basket;
public customer(basket basket){
this.basket=basket;
}
public void run(){
while(true){
basket.pop();
//System.out.println("吃掉:"+cake.toString());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
cake cake=new cake();
basket basket=new basket();
productor productor=new productor(basket);
customer customer=new customer(basket);
productor.start();
Thread th=new Thread(customer);
th.start();
}
}