iteye_19968 2010-03-18 12: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);

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

    }
    }

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

  1. public String toString(){
  2. return "水果:"+id;
  3. }

}
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;
}

  1. public synchronized Fruit Consumption(){
  2. if(indext == 0){
  3. try {
  4. this.wait();
  5. } catch (InterruptedException e) {
  6. e.printStackTrace();
  7. }
  8. }
  9. this.notifyAll();
  10. indext = 1;
  11. return f;
  12. }

}
class Producers implements Runnable{

  1. Method m = null;
  2. public Producers(Method m) {
  3. this.m = m;
  4. }
  5. public void run() {
  6. for(int i=0;i<10;i++){
  7. Fruit f = new Fruit(i);
  8. m.producer(f);
  9. System.out.println("生产水果:"+f);
  10. try {
  11. Thread.sleep((int)Math.random()*200);
  12. } catch (InterruptedException e) {
  13. // TODO Auto-generated catch block
  14. e.printStackTrace();
  15. }
  16. }
  17. }

}

class Customers implements Runnable{

  1. Method m = null;
  2. public Customers(Method m) {
  3. this.m = m;
  4. }
  5. public void run() {
  6. Fruit f = m.Consumption();
  7. System.out.println("消费水果:"+f);
  8. try {
  9. Thread.sleep((int)Math.random()*200);
  10. } catch (InterruptedException e) {
  11. // TODO Auto-generated catch block
  12. e.printStackTrace();
  13. }
  14. }

}
[/code]

展开全部

  • 写回答

1条回答 默认 最新

  • wanghaolovezlq 2010-03-18 12: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();
            }
        }
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部