notify();wait();notifyALL();

来源:互联网 发布:游戏制作软件大全 编辑:程序博客网 时间:2024/05/17 09: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)
  {
   synchronized(r)
   {
    if(!r.flag)
     try
     {
      r.wait();
     }
     catch(Exception e)
     {
     }
    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 = newInput(r);
  Output out = new Output(r);

  Thread t1 = newThread(in);
  Thread t2 = newThread(out);

  t1.start();
  t2.start();
 }
}