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

//创建一个资源  提供两个线程访问
class Person
{
        String name;
        String sex;
        boolean bl = true; //判断资源里边是否已经填充过的变量
}
//创建一个输出对象
class InputDemo implements Runnable
{
        private boolean flag= true;//定义一个变量用来填充不一样的内容
        Person p;
        InputDemo(Person p)
        {
                this.p=p;       
        }
        public void run()
        {
                while(true)
                {
                        synchronized(p)
                        {
                                if(p.bl)
                                {
                                        try{p.wait();}catch(InterruptedException e){}//异常抛出
                                }
                                if(flag)
                                {
                                        p.name="小强";
                                        p.sex ="男";
                                        flag =false;
                                }
                                else
                                {
                                        p.name="弱弱";
                                        p.sex ="女";
                                        flag = true;
                                }
                               
                               
                                p.bl = true;
                                p.notify();
                        }
                }
        }
}
//创建一个输出对象
class Output implements Runnable
{
        Person p ;
        Output(Person p)
        {
                this.p = p;
        }
        public void run()
        {
                while(true){

                        synchronized(p)
                        {
                                if(p.bl)
                                        p.bl = false;
                                System.out.println("姓名:"+p.name+"性别:"+p.sex);
                               
                                try{p.wait();}catch(InterruptedException e){}
                                p.notify();
                        }
                       
                }
                       
        }
}
class ThResource2
{
        public static void main(String[] args)
        {
                Person p = new Person();
                InputDemo in = new InputDemo(p);
                Output out = new Output(p);

                Thread t = new Thread(in);
                Thread t1 = new Thread(out);
                t.start();
                t1.start();

        }
}

0 个回复

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