public class goods {
String name="王芳1",sex="女1";
boolean bFull=false; public synchronized void put(String name,String sex){
if(bFull)
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name=name;
try{
Thread.sleep(10);
}
catch(Exception ex){ex.getMessage();}
this.sex=sex;
bFull=true;
notify();
}
public synchronized void get(){
if(!bFull)//问题出
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} System.out.println(Thread.currentThread().getName()+"--"+name+"-->"+sex);
bFull=false;
notify();
}}public class thead1 {
public static void main(String[]args){
goods g=new goods();
new Thread(new produce(g)).start();
new Thread(new consumer(g)).start();
}}
为什么 把get方法中if(bFull)就不对了,好像进入死锁了!public synchronized void get(){
if(bFull)//这里
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String name="王芳1",sex="女1";
boolean bFull=false; public synchronized void put(String name,String sex){
if(bFull)
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name=name;
try{
Thread.sleep(10);
}
catch(Exception ex){ex.getMessage();}
this.sex=sex;
bFull=true;
notify();
}
public synchronized void get(){
if(!bFull)//问题出
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} System.out.println(Thread.currentThread().getName()+"--"+name+"-->"+sex);
bFull=false;
notify();
}}public class thead1 {
public static void main(String[]args){
goods g=new goods();
new Thread(new produce(g)).start();
new Thread(new consumer(g)).start();
}}
为什么 把get方法中if(bFull)就不对了,好像进入死锁了!public synchronized void get(){
if(bFull)//这里
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
假设produce线程先运行,初始bFull 是 false. 执行下面的语句后 this.name=name;
try{
Thread.sleep(10);
}
catch(Exception ex){ex.getMessage();}
this.sex=sex;
bFull=true;
notify();bFull 为 true.接下来,可能还是这个线程获得执行权(线程的调度的随机性),也可能消费线程获得执行权,假设是后一种情况,执行 if(bFull) 为真,执行下面的语句后 try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}这个消费线程让出同步对象锁,进入等待状态了。这时,生产线程一定会获得运行的权力了,当执行if(bFull)时,也为真,执行下面的语句后try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}这个线程也进入的等待状态了,这样两个线程都在等待状态,没有一个会执行notify(),就这样永远等下去了。
其他情况最后都会是这样的状态。