方式1:
class Resource{
private String name;
private int num=1;
private boolean mark=false;
public synchronized void pro(String name){
if(mark)
try{this.wait();}catch(Exception e){}
//if(!mark){ //加上这句会死锁,死锁位置随机
this.name=name+" ,"+num++;
System.out.println(Thread.currentThread().getName()+" produce comodity: "+this.name);
mark=true;
this.notify();
//}
}
public synchronized void print(){
if(!mark)
try{this.wait();}catch(Exception e){};
//if(mark){//加上这句会死锁,死锁位置随机
System.out.println(Thread.currentThread().getName()+"consume comodity: "+name);
mark=false;
this.notify();
//}
}
}
方式2:
class Resource{
private String name;
private int num=1;
private boolean mark=false;
public synchronized void pro(String name){
while(mark)//加while避免自我唤醒,但是会造成死锁
try{this.wait();}catch(Exception e){}
this.name=name+" ,"+num++;
System.out.println(Thread.currentThread().getName()+" produce comodity: "+this.name);
mark=true;
this.notify();
}
public synchronized void print(){
while(!mark)//加while避免自我唤醒,但是会造成死锁
try{this.wait();}catch(Exception e){};
System.out.println(Thread.currentThread().getName()+"consume comodity: "+name);
mark=false;
this.notify();
}
}