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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 菜鸟征程 中级黑马   /  2015-9-12 23:08  /  488 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class Resource{
       private String name ;
       private String sex ;
       private boolean flag = false;

       public synchronized void set(String name,String sex){
             if(flag )
                   try{
                         this.wait();
                  } catch(InterruptedException e){
                        e.printStackTrace();
                  }
             this.name = name;
             this.sex = sex;
             flag = true ;
             this.notify();
      }
      
      public synchronized void out(){
             if(!flag )
                   try{
                         this.wait();
                  } catch(InterruptedException e){
                        e.printStackTrace();
                  }
             System. out.println(name + "..." + sex);
             flag = false ;
             this.notify();
     }
}

//输入
class Input implements Runnable{
      Resource r;
      Input(Resource r){
             this.r = r;
      }

      public void run(){
             int x = 0;
             while(true ){
                   if(x == 0){
                         r.set( "mike","男" );
                  } else{
                         r.set( "lili","女" );
                  }
                  x = (x + 1)%2;
            }
      }
}

//输出
class Output implements Runnable{
      Resource r;

      Output(Resource r){
             this.r = r;
      }

       public void run(){
             while(true ){
                   r.out();
            }
      }
}

class ResourceDemo {
       public static void main(String[] args){
             //创建资源
            Resource r = new Resource();
             //创建任务
            Input in = new Input(r);
            Output out = new Output(r);
             //创建线程,执行路径
            Thread t1 = new Thread(in);
            Thread t2 = new Thread(out);
             //开启线程
            t1.start();
            t2.start();
      }
}
中间,while(true)这里是当true是执行括号里的还是执行括号里的一直到true为止?

1 个回复

倒序浏览
太高深,看不懂
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马