黑马程序员技术交流社区
标题:
亲们,帮我看看这程序错在哪?
[打印本页]
作者:
天凌蓝
时间:
2014-3-3 10:16
标题:
亲们,帮我看看这程序错在哪?
本帖最后由 天凌蓝 于 2014-3-3 10:19 编辑
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)
{ if (r.flag)
try{r.wait();}catch(Exception e){}
synchronized(r)
{ if(x==0)
{ r.name="nike";
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)
try{r.wait();}catch(Exception e){}
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();
}
}
复制代码
作者:
kira
时间:
2014-3-3 10:30
没有问题啊 你想实现什么效果
作者:
乔青山
时间:
2014-3-3 19:27
if (r.flag)
try{r.wait();}catch(Exception e){}
14,15行代码,就是上面这两行,应该写在同步中,不然会异常
作者:
天凌蓝
时间:
2014-3-6 15:26
乔青山 发表于 2014-3-3 19:27
if (r.flag)
try{r.wait();}catch(Exception e){}
14,15行代码,就是上面这两行,应该写在同步中,不 ...
十分感谢:)
作者:
也许依然
时间:
2014-3-6 16:29
线程t1和t2都会执行wait(),线程之间切换时会出现异常,需要放在同步代码块中执行,也就是14行和15行需要放在同步中
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2