下面的代码是我按照老师的视频打的,可是结果不一样,大家帮忙看下
class Res
{
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable
{
private Res s;
Input(Res s)
{
this.s = s;
}
public void run()
{
//boolean b = true;
int x = 0;
while(true)
{
synchronized(Res.class)
{
if(s.flag)
try{Res.class.wait();}catch(Exception e){}
if(x==0)
{
s.name = "Jack";
s.sex = "man";
//b=false;
}
else
{
s.name = "丽丽";
s.sex = "女";
//b=true;
}
x = (x+1)%2;
s.flag = true;
Res.class.notify();
}
}
}
}
class Output implements Runnable
{
private Res s;
Output(Res s)
{
this.s = s;
}
public void run()
{
while(true)
{
synchronized(Res.class)
{
if(!s.flag)
try{Res.class.wait();}catch(Exception e){}
System.out.println(s.name+"...."+s.sex);
s.flag = true;
Res.class.notify();
}
}
}
}
public class InputOutputDemo
{
public static void main(String[] args)
{
Res s = new Res();
Input i = new Input(s);
Output o = new Output(s);
Thread t1 = new Thread(i);
Thread t2 = new Thread(o);
t1.start();
t2.start();
}
}
|
-
未命名.jpg
(18.08 KB, 下载次数: 27)
这个是运行后的图片
|