线程间的通信

/*线程间的通信
	使用Lock接口,
		condition对象中实现同步中的wait、notify、notifyAll方法,condition对象可以从Lock中的newCondition来获取
	
*/
import java.util.concurrent.locks.*;
class  ProConDemo
{
	public static void main(String[] args) 
	{
		Resource res = new Resource();
		new Thread(new Produce(res)).start();	//匿名创建线程
		new Thread(new Consumer(res)).start();
		new Thread(new Produce(res)).start();
		new Thread(new Consumer(res)).start();
	}
}

class Resource
{
	private String name;
	private int count=0;
	boolean flag = false;	//标志位
	private Lock lock = new ReentrantLock();	
	private Condition condition_pro = lock.newCondition();	//获取一个produce的condition对象
	private Condition condition_con = lock.newCondition();	//获取一个consumer的condition对象

	//Resource(String name){	this.name = name+"...."+count++;	}	
	void set(String name)throws InterruptedException	//condition对象中await()方法会跑出异常
	{	
		lock.lock();
		try
		{
			while(flag)			//当标志变量为true时,即已经生产了,但还没有消费,故要等待
				condition_pro.await();
			this.name = name;
			System.out.println(Thread.currentThread().getName()+this.name+"..生产.."+ ++count);
			flag = true;		//设置true表示已经生产了
			condition_con.signal();	//唤醒consumer中的线程
		}
		finally
		{
			lock.unlock();
		}
	}
	void out()throws InterruptedException
	{	
		lock.lock();
		try
		{
			while(!flag)		//当还没有生产的时候,等待
				condition_con.await();
			System.out.println(Thread.currentThread().getName()+name+"...消费......."+count);
			flag = false;		//标志已经消费了
			condition_pro.signal();		//唤醒produce中的线程
		}
		finally
		{
			lock.unlock();
		}
	}
}

class Produce	implements Runnable
{
	private Resource res;
	Produce(Resource res)
	{
		this.res = res;
	}
	public void run()
	{
		while(true)
		{
			try
			{
				res.set("商品");
			}
			catch (InterruptedException e)
			{
			}
			
		}
	}
}

class Consumer	implements Runnable
{
	private Resource res;
	Consumer(Resource res)
	{
		this.res = res;
	}
	public void run()
	{
		while(true)
		{
			try
			{
				res.out();
			}
			catch (InterruptedException e)
			{
			}
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值