Seek Dream 2022-04-10 21:55 采纳率: 66.7%
浏览 52
已结题

为什么这段程序的notify不起作用?,无法唤醒另一个线程

public class Saletext {
public static void main(String[] args) {
protector p=new protector();
counter c=new counter();
Thread t1=new Thread(p);
Thread t2=new Thread(c);
t1.setName("厂商");
t2.setName("消费者");
t1.start();
t2.start();
}

}

class phone{
Object object=new Object();
int phones=0;
}

class protector extends phone implements Runnable{

@Override
public void run() {
    System.out.println("生产");
    while (true) {
        synchronized (object) {
            if (phones < 20) {
                phones++;
                System.out.println(Thread.currentThread().getName() + "生产第" + phones + "部手机");
                object.notify();
            } else {
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}

}

class counter extends phone implements Runnable{

@Override
public void run() {
    System.out.println("消费");
    while (true) {
        synchronized (object) {
            if (phones >0) {
                System.out.println(Thread.currentThread().getName() + "消费第" + phones + "部手机");
                phones--;
                object.notify();
            } else {
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}

}

  • 写回答

3条回答 默认 最新

  • 离陌lm 2022-04-10 22:06
    关注

    你换成notifyall试试,或者把object加上static,或者同时加

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 4月18日
  • 已采纳回答 4月10日
  • 创建了问题 4月10日