为什么这段程序的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();
                }

            }
        }

    }
}

}

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

把object设置为static变量,否则会产生2个object对象,也可以参考:
https://blog.csdn.net/eve8888888/article/details/84336617

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632