黑马程序员技术交流社区
标题:
多线程,等待唤醒机制
[打印本页]
作者:
盛亚昆
时间:
2012-3-17 18:34
标题:
多线程,等待唤醒机制
多线程,等待唤醒机制中,毕老师说boolean flag默认值是false,那么在同步中if(r.flag)中flag为什么又是ture 了呢
作者:
张一凡
时间:
2012-3-17 18:35
本帖最后由 张一凡 于 2012-3-17 18:50 编辑
因为那个flag定义的是一个标记,判断这个存储的空间里是否为null,为null就是false,反之就是true。
作者:
盛亚昆
时间:
2012-3-17 19:03
class res
{
String name;
String sex;
boolean flag=false;这个flag 是默认错误
}
classIntput implements Runnable
private Res r;
Intput(Res r)
{
this.r=r;
synchronized(r)
{
int x=0
while(true)
{
if(r.flag) ;;;;这里怎么是ture
wait();
if (x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="莉莉";
r.sex="女";
}
x=(x+1)%2
r.flag=true;
notify();
}
}
}
classOutput implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
wait();
System.out.println(r.name+"...."+r.sex);
r.flag=false;
notify();
}
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
Res r=new Res();
Intput=new Intput(r);
Output=new Output(r);
Thread t1=new Thread(in);
Thread t1=new Thread(out);
t1.start();
t2.start();
}
作者:
房宝彬
时间:
2012-3-17 19:10
请仔细阅读楼上的代码,毕老师里的是 if(!r.flag) !的意思是 取反的意思,,false取反就是 true
作者:
盛亚昆
时间:
2012-3-18 10:24
if(!r.flag) !的意思是 取反的意思,但我说的是当它判断的classIntput implements Runnable
if(r.flag) 里时是ture,就是说当给 boolean flag=false负值为false时,这个标记就是内容不为空,就是ture了,呵呵明白了,谢谢了
作者:
张志阳
时间:
2012-3-18 11:59
class res
{
String name;
String sex;
boolean flag=false; //false为默认值,可不写
}
classIntput implements Runnable
private Res r;
Intput(Res r)
{
this.r=r;
synchronized(r)
{
int x=0
while(true)
{
if(r.flag) //此处先判断此时flag是false,不运行wait(),向下运行
wait();
if (x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="莉莉";
r.sex="女";
}
x=(x+1)%2
r.flag=true; //输入之后,flag变为true,但仍有执行权,再向上判断此时这就是你的问题为什么if(r.flag) 中flag为true,运行wait(),输入被此时被冻结
notify();
}
}
}
classOutput implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag) //此时flag已被上面变为true,不运行wait()
wait();
System.out.println(r.name+"...."+r.sex);
r.flag=false; //输出结束后,再把flag值变为false
notify(); //唤醒input,再向上判断flag为false,被冻结。input再次获得执行权,如此循环
}
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
Res r=new Res();
Intput=new Intput(r);
Output=new Output(r);
Thread t1=new Thread(in);
Thread t1=new Thread(out);
t1.start();
t2.start();
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2