雍振
2022-04-10 21:55
采纳率: 66.7%
浏览 37

为什么这段程序的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条回答 默认 最新

相关推荐 更多相似问题