本帖最后由 葛旭东 于 2012-10-8 22:03 编辑
- <p style="line-height: 30px; text-indent: 2em;"></p>
复制代码class Res{
String name;
String sex;
boolean flag = false;
}
class InPut implements Runnable{
private Res r;
InPut(Res r){
this.r = r;
}
public void run(){
int x = 0 ,y = 1;
while(y++<=50000){
synchronized(r){
if(r.flag)
try{r.wait();}
catch(Exception e){}
if(x==0){
r.name = "Tom";
r.sex = "Man";
}
else{
r.name = "丽丽";
r.sex = "女孩女孩";
}
}
x = (x+1)%2;
r.flag = true;
r.notify();
}
}
}
class OutPut implements Runnable{ private Res r;
OutPut(Res r){
this.r = r;
}
public void run(){
int y = 1;
while(y++<=50000){
synchronized(r){
if(!r.flag)
try{r.wait();}
catch(Exception e){}
System.out.println(r.name+"......"+r.sex);
r.flag = false;
r.notify();
}
}
}
}
public class InOutPutDemo {
public static void main(String[] args) {
Res r = new Res();
new Thread(new InPut(r)).start();
new Thread(new OutPut(r)).start();
}
}
;
程序抛出java.lang.IllegalMonitorStateException异常,说明:当前线程不是此对象监视器的所有者;该如何解决?
为什么老毕视频中使用同一锁r的wait()、notify()是可以的呢?
|