写了一个简单的生产者消费者的小程序,我想要的结果是
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();
}
}