码迷,mamicode.com
首页 > 编程语言 > 详细

线程通信

时间:2018-06-19 22:40:27      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:false   ati   art   new   cheng   OLE   on()   fan   new t   

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class person
{
  private String name;
  private String xingbie;
  boolean panduan=false;
  int y=0;
  Lock l=new ReentrantLock();//创建锁。
  Condition c1=l.newCondition();
  Condition c2=l.newCondition();
  public String getName()

  {
    return name;
  }
  public void setName(String name)

   {
    this.name = name;
  }
  public String getXingbie()

   {
    return xingbie;
  }
  public void setXingbie(String xingbie)

  {
    this.xingbie = xingbie;
  }


  public void fangru() throws InterruptedException
  {
    l.lock();
    try

    {

      while(panduan)

      {
        c1.await();
      }
      if(y==0)
      {
        setName("张三");
        setXingbie("男");
      }
    else
    {
      setName("李四");
      setXingbie("女");
    }
    y=(y+1)%2;
    panduan=true;
    c2.signal();
    }
    finally
    {
      l.unlock();
    }

  }

  public void quchu() throws InterruptedException
  {
    l.lock();
    try{
      while(!panduan)
      {
        c2.await();
      }
      System.out.println(this.getName()+"----"+this.getXingbie());
      panduan=false;
      c1.signal();
     }
    finally
    {
      l.unlock();
    }

  }

}

class du implements Runnable
{
  person p;
  du(person p)
  {
    this.p=p;
  }

  public void run()

  {
    while(true)
    {
      try

       {
        p.fangru();
      } catch (InterruptedException e)

       {
        e.printStackTrace();
      }
    }
  }
}
class qu implements Runnable
{
  person p;
  qu(person p)
  {
    this.p=p;
  }
  public void run()

  {
    while(true)
    {
      try

       {
        p.quchu();
      }

       catch (InterruptedException e)

       {
        e.printStackTrace();
      }
    }
  }
}

public class xianchengtongxin

{

  public static void main(String[] args)

   {

    person p=new person();
    du du=new du(p);
    qu qu=new qu(p);
    Thread t1=new Thread(du);
    Thread t2=new Thread(qu);
    Thread t3=new Thread(du);
    Thread t4=new Thread(qu);
    t1.start();
    t2.start();
    t3.start();
    t4.start();
  }

}

线程通信

标签:false   ati   art   new   cheng   OLE   on()   fan   new t   

原文地址:https://www.cnblogs.com/shenhengjia/p/9201201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!