iteye_19968 2010-03-18 20:25
浏览 248
已采纳

java基础,线程同步问题

不知道哪里写错了结果只有:
生产水果:水果:0
消费水果:水果:0
[code="java"]
/**

  • 生产1个水果,卖1个
  • @author 1
    *
    */
    public class NewProducerCustomer {

    public static void main(String[] args) {
    Method m = new Method();
    Producers p = new Producers(m);
    Customers c = new Customers(m);

    new Thread(p).start();
    new Thread(c).start();
    

    }
    }

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

public String toString(){
    return "水果:"+id;
}

}
class Method{
int indext = 0;
Fruit f;
public synchronized void producer(Fruit f){
if(indext == 1){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.f = f;
this.notifyAll();
indext = 0;
}

public synchronized Fruit Consumption(){
    if(indext == 0){
        try {
            this.wait();
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
    }

    this.notifyAll();
    indext = 1;
    return f;
}

}
class Producers implements Runnable{

Method m = null;
public Producers(Method m) {
    this.m = m;
}
public void run() {
    for(int i=0;i<10;i++){

        Fruit f = new Fruit(i);
        m.producer(f);
        System.out.println("生产水果:"+f);

        try {
            Thread.sleep((int)Math.random()*200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

}

class Customers implements Runnable{

Method m = null;
public Customers(Method m) {
    this.m = m;
}
public void run() {
    Fruit f = m.Consumption();
    System.out.println("消费水果:"+f);
    try {
        Thread.sleep((int)Math.random()*200);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}
[/code]

  • 写回答

1条回答 默认 最新

  • wanghaolovezlq 2010-03-18 20:41
    关注

    你的消费者只消费一次就结束了嘛

    public void run() {

    Fruit f = m.Consumption();

    System.out.println("消费水果:"+f);

    try {

    Thread.sleep((int)Math.random()*200);

    } catch (InterruptedException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    }

    改成

    public void run() {
        while(true){
            Fruit f = m.Consumption();
            System.out.println("消费水果:" + f);
            try {
                Thread.sleep((int) Math.random() * 200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?