class PrintMsg
{
public static void main(String[] args)
{
System.out.println("Hello World!");
Msg m = new Msg();
PutIn in = new PutIn(m);
PutOut out = new PutOut(m);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
class Msg
{
String name;
String sex;
boolean flag = false;
}
class PutIn implements Runnable
{
Msg r;
PutIn(Msg r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
synchronized(r)
{
if(r.flag)
try{r.wait();}catch(InterruptedException e){}
if(x==0)
{
r.name = "韩梅梅";
r.sex = "女女女";
}
else
{
r.name = "李雷";
r.sex = "男";
}
r.flag = true;
r.notify();
}
x = (x+1)%2;
}
}
}
class PutOut implements Runnable
{
Msg r;
PutOut(Msg r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
try{r.wait();}catch(InterruptedException e){}
System.out.println(r.name+"......"+r.sex);
r.flag = false;
r.notify();
}
}
}
}
问题:
1.class Msg已经定义flag为false. 那class PutIn中 if(r.flag)和class PutOut中的if(!r.flag)是什么意思呢?
2.PutIn中的r.notify();是不是唤醒的是PutOut中的线程?
3.大括号的书写规范吗? 是不是有些地方不需要另起一行?
4.try catch的书写也不规范?