A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 钟伟杰 中级黑马   /  2012-12-7 12:02  /  1981 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

关于毕老师基础视频day12/03多线程问题,一个关于等待和唤醒机制的问题;
代码如下:
class Res
{
  

  String name;
    String sex;
    boolean flag=false;

}
class Input implements Runnable
{
   private Res r;
   Input(Res r)
{
    this.r=r;
}
int x=0;
public void run()
{
  
  while(true)
  {
   synchronized(r)
   {
    if(r.flag)
     try{r.wait();}catch(Exception e){}
    if(x==0)
    {
     r.name="make";
     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();
}
}

问题:notify语句一定要在有wait对象时才能运行吗,不会出现notify运行完了对象还没进入wait状态吗?{:soso_e103:}

评分

参与人数 1技术分 +1 收起 理由
刘芮铭 + 1

查看全部评分

6 个回复

倒序浏览
{:soso_e128:}重复看了几次视频,估计找到原因了
回复 使用道具 举报
synchronized(r)
   {
    if(r.flag)
     try{r.wait();}catch(Exception e){}
    if(x==0)
    {
     r.name="make";
     r.sex="man";
    }
    else
    {
     r.name="丽丽";
     r.sex="女女";
    }
    x=(x+1)%2;
    r.flag=true;
    r.notify();
   }
  }
}

wait()和notify()是在 synchronized(r){}之内的 是同步的,所以不会出现你所说的情况

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 神马都是浮云

查看全部评分

回复 使用道具 举报
李培根 来自手机 金牌黑马 2012-12-7 20:54:32
板凳
空唤醒是可以存在的。同步结束前修改标记,并notifyAll()确保唤醒对方线程。同理对方线程同步内也会设置标记的修改和notifyAll()

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 神马都是浮云

查看全部评分

回复 使用道具 举报
张向辉 发表于 2012-12-7 18:50
synchronized(r)
   {
    if(r.flag)

明白了,非常感谢
回复 使用道具 举报
李培根 发表于 2012-12-7 20:54
空唤醒是可以存在的。同步结束前修改标记,并notifyAll()确保唤醒对方线程。同理对方线程同步内也会设置标 ...

非常感谢:)
回复 使用道具 举报
钟伟杰 发表于 2012-12-10 07:53
非常感谢

太客气啦。。。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马