代码好乱,好些重复的...
//问题(1):在下面的代码中,为何运行时出错,
public class Threadcomunicate
{
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();
}
}
class Input implements Runnable
{
private res r;
Object obj=new Object();
Input(res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized(r)
{
if(r.flag)
try {r.wait();}catch(Exception e){}
if(x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="lili";
r.sex="women";
}
r.flag=true;
r.notify();
}
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
res r;
Object obj=new Object();
Output(res r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
try {r.wait();}catch(Exception e){}
System.out.println(r.name+".."+r.sex);
r.flag=false;
r.notify();
}
}
}
}
class res
{
String name;
String sex;
boolean flag=false;
} |