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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李哲 中级黑马   /  2012-3-28 18:42  /  1602 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

下面教程实例,我修改了一些代码。

class Res
{
        String name;
        String sex;
        Boolean flag=false;
}

class Input implements Runnable
{
        Object obj=new Object();
        private Res r;
        Input(Res r)
        {
                this.r=r;
        }
        public void run()
        {
                int x=0;
                while(true)
                {
                        synchronized(r)
                        {
                                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.notify();
                        }
                }
        }
}

class Output implements Runnable
{
        Object obj=new Object();
        private Res r;
        Output(Res r)
        {
                this.r=r;
        }
        public void run()
        {
                while(true)
                {
                        synchronized(r)
                        {
                                r.notify();       
                                System.out.println(r.name+"......"+r.sex);
                                try{r.wait();}catch (Exception e){}
                        }
                }
        }
}


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();
               
        }
}


我觉得两个同步代码块里面都有wait(),就应该最多执行一两次,就都等待。
但是为什么有时候运行,还可以打印很多行呢?

2 个回复

倒序浏览
俩线程都睡着了,怎么还会继续呢?所以两个线程都应该加上判断,让其中一个睡着前,叫醒另外一个线程。
output的润方法中加上注释的部分:
// if (!r.flag)
try{r.wait();}catch (Exception e){}     
System.out.println(r.name+"......"+r.sex);
// r.flag = false;  
r.notify();

input的run方法加上注释部分:

//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();
回复 使用道具 举报
lz这里还有r.notify()。
r.wait()让线程等待,r.notify()唤醒等待线程当然会输出多行。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马