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

© 插兜 中级黑马   /  2015-9-16 18:20  /  340 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class InputOutputDemo
{
        public static void main(String[] args)
        {
                Res r=new Res();
                Input in=new Input(r);
                Output out=new Output(r);
                Thread t1=new Thread(in);
                Thread t2=new Thread(out);
                t1.start();
                t2.start();
        }
}

class Res
{
        String name;
        String sex;
        boolean flag=false;
}
class Input implements Runnable
{
        private Res r;
        Input(Res r)
        {
                this.r=r;
        }
        public void run()
        {
                int x=0;
                while(true)
                {
                        synchronized(r)
                        {
                                if(r.flag)
                                        try{r.wait();}catch(Exception e){}
                                if (x==0)
                                {
                                        r.name="mike";
                                        r.sex="man";
                                }
                                else
                                {
                                        r.name="丽丽";
                                        r.sex="女女女女女";
                                }
                                x=(x+1)%2;
                                r.flag=true;
                                r.notify();
                        }
                }
        }
}
class Output implements Runnable
{
        private Res r;
        Output(Res r)
        {
                this.r=r;
        }
        public void run()
        {
                while(true)
                {
                        synchronized(r)
                        {
                                if(!r.flag)
                                        try{r.wait();}catch(Exception e){}
                                System.out.println(r.name+"----"+r.sex);
                                r.flag=false;
                                r.notify();
                        }
                }
        }
}
您需要登录后才可以回帖 登录 | 加入黑马