y460551890 2015-03-24 12:41 采纳率: 100%
浏览 2008
已采纳

java notify 唤醒 wait没有反应

写了一个简单的生产者消费者的小程序,我想要的结果是
producer1 1
consumer1 0
但结果只出现了producer1 1
调试的时候发现,消费者consumer1在进入wait()后没有被唤醒,不知道是为什么,请大神帮忙解答

 class Holder{
    private int productionNumber=0;
    private int max=10;
    private int min=0;
    public int getNum(){
        return productionNumber;
    }
    public synchronized void addNum(){
        try{
            if(productionNumber>=max){
                wait();
            }   
            else{
                productionNumber++;
                System.out.println(Thread.currentThread().getName()+"  "+productionNumber);
                this.notify();
            }
        }
        catch(InterruptedException ex){
            ex.printStackTrace();
        }
    }
    public synchronized void subNum(){
        try{
            if(productionNumber<=min){

                wait();
            }   
            else{

                productionNumber--;
                System.out.println(Thread.currentThread().getName()+"  "+productionNumber);
                this.notify();
            }
        }
        catch(InterruptedException ex){
            ex.printStackTrace();
        }
    }
}

class Producer extends Thread{
    Holder holder;
    public Producer(String threadName,Holder holder){
        super(threadName);
        this.holder=holder;
    }
    public void run(){
        holder.addNum();

    }
}

class Consumer extends Thread{
    Holder holder;
    public Consumer(String threadName,Holder holder){
        super(threadName);
        this.holder=holder;
    }
    public void run(){
        holder.subNum();
    }
}

public class TestThread5{
    public static void main(String[] args){
        Holder one=new Holder();

        new Consumer("consumer1",one).start();
        new Producer("producer1",one).start();

    }
}
  • 写回答

1条回答 默认 最新

  • danielinbiti 2015-03-24 14:50
    关注

    注意,唤醒后是执行wait后的代码,而不是wait所在的方法重新执行,所以不会打印else中的信息。
    这代码得改一下,addnum也一样

     public synchronized void subNum(){
            try{
                while(productionNumber<=min){
    
                    wait();
                }   
    
    
                                productionNumber--;
                                System.out.println(Thread.currentThread().getName()+"  "+productionNumber);
                                this.notify();
            }
            catch(InterruptedException ex){
                ex.printStackTrace();
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?