黑马程序员技术交流社区

标题: 多线程中线程等待唤醒问题 [打印本页]

作者: 黑马十八期0513    时间: 2012-12-1 10:35
标题: 多线程中线程等待唤醒问题
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)
  {
   if(!r.flag)
    try{r.wait();}catch(Exception e){}
   synchronized(r)
   {
    System.out.println(r.name+"..."+r.sex);
    r.flag =false;
    r.notify();
   }
  }
}
}

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

有两个问题:
1
class Input implements Runnable
{
private Res r;
Input(Res r)
{
  this.r =r;
}

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

这两段代码是怎么想出来的?我看着都感觉很难理解的,这是怎么想出来的?

2 为什么我的运行结果不对?没有达到输入一个输出一个的结果。代码中哪儿出了问题?


未命名.jpg (56.14 KB, 下载次数: 41)

连续打印出多个丽丽女

连续打印出多个丽丽女

作者: 冯盼    时间: 2012-12-1 11:26
1.那两段代码是为了使得两个类使用同一个Res实例出的对象,否各自使用各自的资源对象,这两个线程就不是在操作同一个数据资源了。

2.你的代码:
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();
                        }
                }
        }
}
作者: 梁枝武    时间: 2012-12-1 11:42
1)当你在main方法中 Res r =new Res();的时候产生了共享资源对象 r
2) Input in =new Input(r);Output out =new Output(r);将 r 分别传入 Input 和 Output的构造函数
3)通过调用构造函数将传入的对象引用分别赋给 Input 和 Output  内部使他们两产生的对象in和out持有相同的引用,即两个run方法可以操作同一资源





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2