解决一下下面代码出现问题的原因:
//共享数据
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();
}}
//共享数据
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();
}}
this.wait(); --> d.wait();
this.notifyAll(); ---> d.notifyAll();全部替换一下
也就是4楼说的
this.wait(); --> d.wait();
this.notifyAll(); ---> d.notifyAll();
就可以了。加个synchronized就能使线程是对象锁的所有者吗?可以这样说
因为加了synchronized以后,进入synchronized区域代码的线程必须要先获得此对象的对象锁(synchronized方法类似)。