黑马程序员技术交流社区
标题:
问个if问题
[打印本页]
作者:
谭荣强
时间:
2014-2-24 02:09
标题:
问个if问题
多线程里的if问题,在inPut类中,那个加注释的else不去掉运行结果就错误,毕老师就没写else,有无else有区别吗,
class Res
{
boolean flag=false;
String name;
String sex;
}
class inPut implements Runnable
{
int x=0;
Res r;
inPut(Res r)
{
this.r=r;
}
public void run()
{
while (true)
{
synchronized(r)
{
if(r.flag)
{
try
{
r.wait();
}
catch (Exception e)
{
}
}
else//去掉else就没事了
if (x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="丽丽";
r.sex="女...";
}
r.flag=true;
r.notify();
}
x=(x+1)%2;
}
}
}
class outPut implements Runnable
{
Res r;
outPut(Res r)
{
this.r=r;
}
public void run()
{
while (true)
{
synchronized(r)
{
if (!r.flag)
try
{
r.wait();
}
catch (Exception e)
{
}
else
{
System.out.println(r.name+r.sex);
r.flag=false;
r.notify();
}
}
}
}
}
class lianxi
{
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();
}
}
作者:
夏新¤Amoi
时间:
2014-2-24 12:40
运行结果错误是很正常的。
if的循环语句有两种,if...else...和if...else if...else...。去掉了else是有了两个判读,不去就是一个判断了。
这个程序在这两种情况下的运行结果肯定是不一样的。
作者:
无道
时间:
2014-2-26 14:25
我的是理解是:如果你加上else,当false值为假时才会执行下面的if语句,,如果为真时,线程就会等待,如果没有else 当false值为真或假时都会执行if语句。if语句里的代码不管false为真或假时它都 要执行的。
作者:
yekong262
时间:
2014-2-26 15:53
不知道回答的是否正确
if(r.flag)
{
try
{
r.wait();
}
catch (Exception e)
{
}
}
else//如果没去掉 下面画红色的语句就是else语句中的内容
if (x==0)
{
r.name="mike";
r.sex="man";
}
else//这里就是无效语句
{
r.name="丽丽";
r.sex="女...";
}
作者:
年少丶
时间:
2014-2-28 20:03
if,else if都需要接判断表达式。else不需要判断表达式。
使用else if和else,必须紧跟在if之后,形参if-esle if组或if-else对。 没有对应的if语句,else if和else语句都会在编译时报错。
if(condition1) /*如果满足条件1*/
{
}
else if(condition2)/*否则,如果满足条件2*/
{
}
else/*否则*/
{
}
作者:
向阳泪无痕
时间:
2014-3-1 08:47
我看了下 是你的if 。。。else 结构 不对 把你说的这句 else//去掉else就没事了 这句后加上{}把你后面的代码放进行去 就没问题了。。。不然结构有问题
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2