class Res
{
private String name;
private String sex;
private boolean flag=false;
public synchronized void set(String name,String sex)
{
if(flag)
try{this.wait();}catch(Exception e){}
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
public void out()
{
if(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(name+"...."+sex);
flag=false;
this.notify();
}
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
r.set("mike","man");
else
r.set("lili","woman");
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
Res r=new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
这是比老师多线程数据通信的代码。我按照这个编译没有问题,可是运行的时候就只跑了一行,然后收到这样的提示。郁闷啊。
mike....man
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at Res.out(InputOutputDemo.java:48)
at Output.run(InputOutputDemo.java:83)
at java.lang.Thread.run(Thread.java:745)
|