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

© 小p 中级黑马   /  2015-7-21 16:52  /  168 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*
线程间通讯:
其实就是过个线程在操作同一个资源
只是操作动作不同
*/
class Res
{
  String name;
  String sex;
  boolean flag=false;
}

class Input implements Runnable
{
//Res r=new Res();这样创建对象不能保证是操作的同一个对象。
//通过建立私有引用保证了操作的是同一个对象。
private Res r;
//Object obj=new Object();
Input(Res r)
{
  this.r=r;
}
public void run()
{
  int x=0;
  while(true)
  {
   synchronized(r)
   {
    while(r.flag)//用while和notifyAll避免了多个生产者和消费者这类的问题
     try {r.wait();}catch(Exception e){}
    //wait方法在object类中抛出了异常所以必须要try。
    if(x==0)
    {
     r.name="mike";
     r.sex="man";
    }
    else
    {
     r.name="丽丽";
     r.sex="女女女女";
    }
    x=(x+1)%2;
    r.flag=true;
    r.notifyAll();
   }
  }
}
}
class Output implements Runnable
{
//Res r=new Res();
private Res r;
//Object obj=new Object();
Output(Res r)
{
  this.r=r;
}
public void run()
{
  while (true)
  {
   synchronized(r)
   {
    whlie(!r.flag)
     try {r.wait();}catch(Exception e){}
    System.out.println(r.name+"...."+r.sex);
    r.flag=false;
    r.notifyAll();
   
   }
  }
}
}
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();
}
}

0 个回复

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