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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张利 中级黑马   /  2012-9-13 22:42  /  1264 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 张利 于 2012-9-14 00:39 编辑

class Res
{
        private String name;
        private String sex;
        private boolean flag;
        
        public synchronized void set(String name,String sex)
        {
                if(flag)
                        try{this.wait();}catch(Exception e){}
                this.name = name;
                this.sex = sex;
                flag = true;
                this.notify();
        }

        public synchronized void out()
        {
                if(!flag)
                        try{this.wait();}catch(Exception e){}
                System.out.println(name+"......"+sex);
                flag = false;
                this.notify();
        }
}

class Input implements Runnable
{
        private Res r;
        Input(Res r)
        {
                this.r=r;
        }
        public void run()
        {
                int x =0;
                while(true)
                {
                        if (x==0)
                                r.set("mike","nan");
                        else
                                r.set("丽丽","女女");
                        x = (x+1)%2;
                                
                }
                        
                        
               
               
        }
}

class Output implements Runnable
{
        
        private Res r;
        Output(Res r)
        {
                this.r=r;
        }

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

class  InputOutputDemoYH
{
        public static void main(String[] args)
        {
                Res r = new Res();
               
                new Thread(new Input(r)).start();
                new Thread(new Output(r)).start();        
        }
}

跟着视频一块块的打出来的 可是运行结果是打印一句之后就锁住了 看代码也没找到是哪里的问题。。。。。。。

3 个回复

倒序浏览
input 里面  while(true) 死循环
回复 使用道具 举报
本帖最后由 王金科 于 2012-9-13 23:14 编辑
  1. public void run()
  2.         {
  3.                 while(true){
  4.                         r.out();
  5.                 }
  6.         }
复制代码
OutPut里的代码改成这样就行了
你的代码里,OutPut线程只转了一次就停了
回复 使用道具 举报
class Output implements Runnable
{
        
        private Res r;
        Output(Res r)
        {
                this.r=r;
        }

        public void run()
        {
           while(true){     没有while循环,当然只打印一次了。
                                 以后都不再走out方法,所以就无法唤醒Inpuut,所以线程一直等待

                r.out();
            }
        }
}

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