JAVA 线程通信以及多个生产者消费者模型

       今天讲讲JAVA线程通信问题,相信学过操作系统的都知道进程线程的通信。仅仅Linux下就有管道,消息队列,信号,信号量,共享内存,socker 等等。

        在JAVA虚拟机中,有一种类似于linux下PV原语的通信。

        

        建模型

        今有两人工作于流水线,一人给流水线上的物品命名,一人给在命名完后输出。

  

      

class Resources
{
	String name;
	String sex;
	boolean flag = false;
}


class Producer implements Runnable
{
	Resources r;
	int x = 0;
	Producer(Resources r)
	{
		this.r = r; 
	}
	public void run()
	{
	 
	   while(true)
	   {
		  synchronized(r)
		  {
		   if(r.flag)
		   {
		   try{
			   r.wait();
		   }
		   catch(InterruptedException e){}
		   }

		   if(x == 0)
		   {
			   r.name = "mary";
			   r.sex= "girl";
		   }
			   
		   else
		   {
			   r.name = "mike";
			   r.sex = "boy";
		   }
		   /*
		   if( x ==  0)
		    x = 1;
		   else
			x = 0;*/
			x = (++x) % 2;
		   System.out.println("x is "+x);

		   System.out.println("now i set the name is "+ r.name +" set the sex is "+r.sex);
		   r.flag = true ; 
		   r.notify();
		  }
		 
	   }
	}
			   
}
		   

class Customer implements Runnable
{
	Resources r;
	Customer(Resources r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
		 synchronized(r)
		 {
		   if(!r.flag)
		   {
		   try{
			   r.wait();
		   }
		   catch(InterruptedException e){}
		   }
		  
		   System.out.println("output name is "+r.name+"output sex is "+r.sex);
		   r.flag = false;
		   r.notify();
		 }
		}
	}
}



class  Thread_test 
{
	public static void main(String[] args) 
	{
		Resources r = new Resources();
		Producer p1 = new Producer(r);
		Customer p2 = new Customer(r);
		Thread t1 = new Thread(p1);
		Thread t2 = new Thread(p2);
		t1.start();
		t2.start();
	//	System.out.println("Hello World!");
	}
}

OUTPUT::

now i set the name is mary set the sex is girl
output name is maryoutput sex is girl
x is 0
now i set the name is mike set the sex is boy
output name is mikeoutput sex is boy
x is 1
now i set the name is mary set the sex is girl
output name is maryoutput sex is girl
x is 0
now i set the name is mike set the sex is boy
output name is mikeoutput sex is boy
x is 1

未完待续

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值