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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 天凌蓝 中级黑马   /  2014-3-3 10:16  /  1130 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 天凌蓝 于 2014-3-3 10:19 编辑
  1. class Res
  2. {         String name;
  3.          String sex;
  4.          boolean flag=false;
  5. }
  6. class Input implements Runnable
  7. {        private Res r;
  8.         Input(Res r)
  9.         {        this.r=r;
  10.         }
  11.         public void run()
  12.         {        int x=0;
  13.                 while (true)
  14.                 {        if (r.flag)
  15.                                 try{r.wait();}catch(Exception e){}
  16.                         synchronized(r)
  17.                         {        if(x==0)
  18.                                 {        r.name="nike";
  19.                                         r.sex="man";
  20.                                 }else
  21.                                 {        r.name="丽丽";
  22.                                         r.sex="女女女女";
  23.                                 }
  24.                                 x=(x+1)%2;
  25.                                 r.flag=true;
  26.                                 r.notify();
  27.                         }
  28.                 }
  29.         }
  30. }
  31. class Output implements Runnable
  32. {
  33.         private Res r;
  34.         Output(Res r)
  35.         {        this.r=r;
  36.         }
  37.         public void run()
  38.         {        while(true)
  39.                 { synchronized(r)
  40.                         {  if(!r.flag)
  41.                                         try{r.wait();}catch(Exception e){}
  42.                                 System.out.println(r.name+"...."+r.sex);
  43.                                 r.flag=false;
  44.                                 r.notify();
  45.                         }
  46.                 }
  47.         }
  48. }
  49. class  InputOutputDemo
  50. {
  51.         public static void main(String[] args)
  52.         {        Res r=new Res();
  53.                 Input in=new Input(r);
  54.                 Output out=new  Output(r);
  55.                 Thread t1=new Thread(in);
  56.                 Thread t2=new Thread(out);
  57.                 t1.start();
  58.                 t2.start();
  59.         }
  60. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
zzkang0206 + 1

查看全部评分

4 个回复

倒序浏览
没有问题啊 你想实现什么效果
回复 使用道具 举报
if (r.flag)
    try{r.wait();}catch(Exception e){}
14,15行代码,就是上面这两行,应该写在同步中,不然会异常

评分

参与人数 1技术分 +1 收起 理由
zzkang0206 + 1

查看全部评分

回复 使用道具 举报
乔青山 发表于 2014-3-3 19:27
if (r.flag)
    try{r.wait();}catch(Exception e){}
14,15行代码,就是上面这两行,应该写在同步中,不 ...

十分感谢:)
回复 使用道具 举报
线程t1和t2都会执行wait(),线程之间切换时会出现异常,需要放在同步代码块中执行,也就是14行和15行需要放在同步中
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马