线程通信

Posted shenhengjia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程通信相关的知识,希望对你有一定的参考价值。

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

}





















































































































以上是关于线程通信的主要内容,如果未能解决你的问题,请参考以下文章

iOS开发多线程篇—线程间的通信

13.6 线程通信

13.6 线程通信

等待与唤醒机制(线程之间的通信)

Java 多线程线程间的通信

Java进程间通信和线程间通信?