//创建一个商店,并用它的对象作为后面的同步监视器
class Store{
int product;
}
//创建生产者类
class Producer implements Runnable{
Store store;
public Producer(Store store){
this.store = store;
}
@Override
public void run() {
while(true){
synchronized(store){
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
    if(store.product >= 20){
    store.notify();
    try {
    store.wait();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    store.product++;
    System.out.println(Thread.currentThread().getName() + ":" + "生产了第" + store.product + "个产品");
}
}

}
}
//消费者
class Consumer implements Runnable{
Store store;
public Consumer(Store store){
this.store = store;
}
@Override
public void run() {
while(true){
synchronized(store){
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
    if(store.product <= 0){
    store.notify();
    try {
    store.wait();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    store.product--;
    System.out.println(Thread.currentThread().getName() + ":" + "消费了第" + (store.product + 1) + "个产品");
}
}

}

}public class ProducerAndConsumer {
public static void main(String[] args) {
Store s = new Store();
Producer p = new Producer(s);
Consumer c = new Consumer(s);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
Thread t3 = new Thread(c);
Thread t4 = new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}}
//运行时,如果只有一个生产者和一个消费者则没问题,多了几个就会产生负数。

解决方案 »

  1.   

    额,我知道了。是notify()写错了地方,写到if语句里了。
      

  2.   

    synchronized(store){
        if(store.product <= 0){
        store.notify();   在这notify的话,假设生产者wait了然后产品被一直消费到零之后,才会进入if语句,那时才会把生产者唤  醒。而且把生产者
         //唤醒后,假设它运气不好,cpu又被其它的消费者抢到后,假设是消费者2号,此时产品还是零,于是消费者2号也会进入if语句反而把前面进入的消费者1唤
         //醒(因为只有它是wait着的),接着消费者1把产品减为-1。如果生产者一直运气不好,那么这些消费者就轮流进入if语句把对方唤醒,自己再wait,对方再继续减产品。
        try {
        store.wait();
        } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        }
        store.product--;
        System.out.println(Thread.currentThread().getName() + ":" + "消费了第" + (store.product + 1) + "个产品");
        
    }