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;
while(true)
{
synchronized(r)
{
if(r.flag) //r.flag==false 因为flag默认值为false,当t1线程执行到这,r.flag==false为true,t1进入冻结状态,flag标记没有改变;
//continue; try{r.wait();}catch(Exception e){}
if(x==0)
{
r.name="mike";
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()
{
while(true)
{
synchronized(r)
{
if(!r.flag) //r.flag==false 当t2线程运行时,r.flag==false还是为true,t2进入冻结状态,自此,t1和t2线程都进入冻结状态, try{r.wait();}catch(Exception e){}; //continue
System.out.println(r.name+"...."+r.sex);
r.flag = false;
r.notify();
}
}
}
}
class j
{
public static void main(String[] args)
{
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
上方红色字体部分,经过改动 |