class  waitandnotify
{
public static void main(String[] args) 
{
Resources r=new Resources();
Input in=new Input(r);
Output ou=new Output(r);
Thread t=new Thread(in);
Thread t1=new Thread(ou);
t.start();
t1.start();
}
}
class Resources
{
String name;
String sex;
boolean flag=false;
}
class Input implements Runnable
{
Resources r;
Input(Resources r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized(r)
{
if(r.flag) //{  问题①:
         //[if后面加上"{}",运行没数据]:为什么我不能加“{}”来规范if语句?我的理解是:既然if后面的都要执行,我加上"{}"来包住它们应该没问题吧;
//{  问题②:
//[只把"{}"包住try'catch部分,没问题]:为什么呢?难道if语句块只管try‘catch部分?
//   问题③:[按照问题②的想法,这if语句块可以移动吗?]于是我把if和try’catch部门一起移动到r.flag的前面。结果有问题。
//if(r.flag)
//{
//try{r.wait();}catch (InterruptedException e){}
//}
try{r.wait();}catch (InterruptedException e){}
//}
if(x==0)
{
r.name="张三";
r.sex="男";
}
else
{
r.name="lisi";
r.sex="nv";
}
r.flag=true;
r.notify();
//}

}
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
Resources r;
Output(Resources r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
//{  问题①:
//[if后面加上"{}",运行没数据]:为什么我不能加“{}”来规范if语句;我的理解是:既然if后面的都要执行,我加上"{}"来包住它们应该没问题吧;
//{  问题②:
//[只把"{}"包住try'catch部分,没问题]:为什么呢?难道if语句块只管try‘catch部分?
try{r.wait();}catch (InterruptedException e){}
//}
System.out.println(r.name+".."+r.sex);
r.flag=false;
r.notify();
//}
}
}
}
}拜托有心人替我讲解一下!谢谢!javaeewait()notify()