开机阿飞 2017-05-09 13:09 采纳率: 0%
浏览 809

新手请教 关于Java多线程 wait notify的问题

class PrintMsg
{
public static void main(String[] args)
{
System.out.println("Hello World!");
Msg m = new Msg();

    PutIn in = new PutIn(m);
    PutOut out = new PutOut(m);

    Thread t1 = new Thread(in);
    Thread t2 = new Thread(out);

    t1.start();
    t2.start();

}

}
class Msg
{
String name;
String sex;
boolean flag = false;
}
class PutIn implements Runnable
{
Msg r;
PutIn(Msg r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
synchronized(r)
{
if(r.flag)
try{r.wait();}catch(InterruptedException e){}
if(x==0)
{
r.name = "韩梅梅";
r.sex = "女女女";
}
else
{
r.name = "李雷";
r.sex = "男";
}
r.flag = true;
r.notify();

        }
        x = (x+1)%2;
    }
}

}
class PutOut implements Runnable
{
Msg r;
PutOut(Msg r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
try{r.wait();}catch(InterruptedException e){}
System.out.println(r.name+"......"+r.sex);
r.flag = false;
r.notify();
}
}
}

}

问题:
1.class Msg已经定义flag为false. 那class PutIn中 if(r.flag)和class PutOut中的if(!r.flag)是什么意思呢?
2.PutIn中的r.notify();是不是唤醒的是PutOut中的线程?
3.大括号的书写规范吗? 是不是有些地方不需要另起一行?
4.try catch的书写也不规范?

  • 写回答

1条回答 默认 最新

  • 差点九零后 2017-05-09 14:07
    关注

    回答:
    1、if(r.flag ) 和 if( !r.flag) 就是一个条件判断 如果含义就是 条件为真,线程体才会执行
    2、是的
    3、对于大括号的书写规范,没有明确的规定!不同公司也会不同。但是我个人更加接受 if判断只有一行代码中不加大括号,一行以上加括号。
    对于换行问题,我习惯
    if(){

            }
            这样的格式
        对于这个建议你看看百度公开的java编程规范,有很好的建议和说明
    

    4、同建议 百度一下,下载可以认真看看哦!!!

    ---纯手写,望采纳。

    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型