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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 焦亚星 中级黑马   /  2013-2-3 14:37  /  1275 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 焦亚星 于 2013-2-4 10:35 编辑

以下代码中的等待和唤醒是不是可以省略:  执行set()或out()中一个方法执行时,另一个是进不来的
  1. class Res
  2. {
  3.         private String name;
  4.         private String sex;
  5.         private boolean flag = false;

  6.         public synchronized void set(String name,String sex)
  7.         {
  8.                 if(flag)
  9.                         try{this.wait();}catch(Exception e){}
  10.                 this.name = name;
  11.                
  12.                 this.sex = sex;
  13.                 flag = true;
  14.                 this.notify();
  15.         }
  16.         public synchronized void out()
  17.         {
  18.                 if(!flag)
  19.                         try{this.wait();}catch(Exception e){}
  20.                 System.out.println(name+"........"+sex);
  21.                 flag = false;
  22.                 this.notify();
  23.         }
  24. }

  25. class Input implements Runnable
  26. {
  27.         private Res r ;
  28.         Input(Res r)
  29.         {
  30.                 this.r = r;
  31.         }
  32.         public void run()
  33.         {
  34.                 int x = 0;
  35.                 while(true)
  36.                 {
  37.                         if(x==0)                                
  38.                                 r.set("mike","man");                                
  39.                         else        
  40.                                 r.set("丽丽","女女女女女");                                
  41.                         x = (x+1)%2;
  42.                 }
  43.         }
  44. }

  45. class Output implements Runnable
  46. {
  47.         private Res r ;
  48.         
  49.         Output(Res r)
  50.         {
  51.                 this.r = r;
  52.         }
  53.         public void run()
  54.         {
  55.                 while(true)
  56.                 {
  57.                         r.out();
  58.                 }
  59.         }
  60. }


  61. class  InputOutputDemo2
  62. {
  63.         public static void main(String[] args)
  64.         {
  65.                 Res r = new Res();
  66.                 new Thread(new Input(r)).start();
  67.                 new Thread(new Output(r)).start();
  68.                 }
  69. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
冯海霞 + 1

查看全部评分

2 个回复

倒序浏览
他这里的目的不仅仅是实现同步 还有让结果交替打印吧.
回复 使用道具 举报
楼上说的对!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马