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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 易东俊 中级黑马   /  2014-10-21 21:09  /  716 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package Res;
class ResDemo
{
        public static void main(String[] args)
        {
                Res r = new Res();
                Input i = new Input(r);
                Output o = new Output(r);
                Thread t1 = new Thread(i);
                Thread t2 = new Thread(o);
                t1.start();
                t2.start();
        }
}
class Res
{
        boolean flag = false;
        String name;
        String sex;
}
class Input implements Runnable
{
        private Res r;
        Input(Res r)
        {
                this.r = r;
        }
        public void run()
        {
                        int num = 0;
                        while(true)
                        {
                                while(r.flag)
                                        try{wait();}catch(Exception e){}
                                num = ++num % 2;
                                if(num == 0)
                                {
                                                r.name = "张三";
                                                r.sex = "男";
                                }
                                else
                                {
                                                r.name = "LiXue";
                                                r.sex = "girl";
                                }
                                r.flag = true;
                                //try{notify();}catch(Exception e){}       
                        }
        }
}
class Output implements Runnable
{
        private Res r;
        Output(Res r)
        {
                this.r = r;
        }
        public void run()
        {
                        while(true)
                        {
                                while(!r.flag)
                                        try{wait();}catch(Exception e){}
                                        System.out.println(r.name+"...... "+r.sex);
                                r.flag = false;
                                //try{notify();}catch(Exception e){}       
                        }
        }               
}
打印结果是什么?我不理解结果

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马