解决一下下面代码出现问题的原因:
//共享数据
class Data { int amount = 0;}//生产类
class Producer extends Thread {
Data d; Producer(Data d) {
this.d = d;
} public void run() {
synchronized (d) {
while (true) {
if (d.amount > 0) {
System.out.println("产品有剩余,停止生产");
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

}else{
d.amount++;
System.out.println("开始生产");

}
}
}
}}//销售类
class Seller extends Thread{ Data d;
Seller(Data d){
this.d=d;
}
public void run(){
synchronized(d){
while(true){
if(d.amount>0){
d.amount--;
System.out.println("卖出产品");
}else{
System.out.println("没有产品,停止出售");
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}//测试类
public class Test {
public static void main(String args[]){
Data d=new Data();
Producer p1=new Producer(d);
Seller s2= new Seller(d);
p1.start();
s2.start();
}}

解决方案 »

  1.   

    用什么synchronized,  就用什么wait和notifyAll
      

  2.   

    自己看看吧http://blog.163.com/fan_yishan/blog/static/47692213200881981424126/
      

  3.   


    this.wait();  --> d.wait();
    this.notifyAll();  ---> d.notifyAll();全部替换一下
      

  4.   

    怎么理解这句话:如果当前的线程不是此对象锁的所有者,却调用该对象的notify(),notify(),wait()方法时抛出该异常。加个synchronized就能使线程是对象锁的所有者吗?
      

  5.   

    怎么理解这句话:如果当前的线程不是此对象锁的所有者,却调用该对象的notify(),notify(),wait()方法时抛出该异常。加个synchronized就能使线程是对象锁的所有者吗?
      

  6.   

    怎么理解这句话:如果当前的线程不是此对象锁的所有者,却调用该对象的notify(),notify(),wait()方法时抛出该异常。加个synchronized就能使线程是对象锁的所有者吗?
      

  7.   

    你的wait和notifyAll要在获得锁的 对象进行,也就是你synchronized(d)中d引用的Data对象。
    也就是4楼说的
    this.wait(); --> d.wait();
    this.notifyAll(); ---> d.notifyAll();
    就可以了。加个synchronized就能使线程是对象锁的所有者吗?可以这样说
    因为加了synchronized以后,进入synchronized区域代码的线程必须要先获得此对象的对象锁(synchronized方法类似)。