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)
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)
{
if(!r.flag)
try{r.wait();}catch(Exception e){}
synchronized(r)
{
System.out.println(r.name+"..."+r.sex);
r.flag =false;
r.notify();
}
}
}
}
class InputOutputDemo
{
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();
}
}
有两个问题:
1
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r =r;
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r =r;
}
这两段代码是怎么想出来的?我看着都感觉很难理解的,这是怎么想出来的?
2 为什么我的运行结果不对?没有达到输入一个输出一个的结果。代码中哪儿出了问题?
|
-
未命名.jpg
(56.14 KB, 下载次数: 45)
连续打印出多个丽丽女
|