多线程实现,生产者和消费者吃蛋糕问题。我认为问题出在类cake上,但是不会改,希望大神能给予帮助,谢谢

小仙女1228 小仙女1228 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
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();

}

}
...全文

相关推荐

评论 1
收藏 已收藏
分享
返回顶部
小仙女1228
Java SE 62,620 成员 307,251 内容