黑马程序员 利用Lock Condition解决多生产者多消费者问题的实例

------- android培训java培训、期待与您交流! ----------多生产者,多消费者
JDK1.5后解决多生产者与消费者问题
java.util.concurrent.locks 包下的
Lock:  
Lock 实现提供了比使用 synchronized 方法和语句可获得的更广泛的锁定操作
Condition 
Condition 将 Object 监视器方法(wait、notify 和 notifyAll)分解成截然不同的对象,
以便通过将这些对象与任意 Lock 实现组合使用
Condition中的 await  signal  signalAll
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class Demo7
{
	public static void main(String[] args) throws Exception
	{
		//创建资源
		Resource r=new Resource();

		Production p=new Production(r);

		Customer c=new Customer(r);

		Thread t1=new Thread(p); //生产者
		Thread t2=new Thread(c); //消费者
		Thread t11=new Thread(p); //生产者
		Thread t22=new Thread(c); //消费者
	

		t2.start();
		t22.start();
		Thread.sleep(10);
		t1.start();
		t11.start();
	}
}


//资源
class Resource
{
	private String name; //产品名称

	private int num1=1;//产品序号
	private int num2=1;//消费序号
	private boolean flag; //如果为false代表 消费过  应该进行生产
						  //如果为true代表   生产过,应该进行消费	
	//获得Lock对象

	Lock l=new ReentrantLock(); //得到一个锁对象

	//获得这个锁的监视器对象 

	  Condition c=l.newCondition(); //处理生产

	  Condition cc=l.newCondition(); //处理消费

	//生产方法
	public  void pro(String name){
		
		l.lock();//加锁
		try{
		while(flag){
			c.await();//通过c监视器来让生产线程等待
		}

		this.name=name;
		System.out.println(Thread.currentThread().getName()+" 生产产品"+this.name+(num1++) );
		
		flag=true;//生产过

			cc.signal();//唤醒消费
		}catch(InterruptedException e){
		
		}finally{
			l.unlock();
		}
	}
	//消费方法
	public  void cus(){
		l.lock();//加锁
		try{
		while(!flag){
			cc.await();//通过cc监视器让消费线程等待
		}

		System.out.println(Thread.currentThread().getName()+" 消费产品"+this.name+(num2++));
		
		flag=false;//消费过

		c.signal(); //唤醒生产
		
		}catch(InterruptedException e){
		
		}finally{
			l.unlock();
		}
	}

}

//生产者
class Production implements Runnable
{
	private Resource r;

	public Production(Resource r){
		this.r=r;
	}

	public void run(){
		while(true){
			r.pro("面包");//调用生产
		}
	}
}

//消费者
class Customer implements Runnable
{
	private Resource r;

	public Customer(Resource r){
		this.r=r;
	}

	public void run(){
		while(true){
			r.cus();//调用消费
		}
	}

}


使用jdk1.5后这些锁对象与监视对象,最大的一个好处是操作列简单,
并且一个锁可以对应多个监视器,也就是说,我们在生产时,应该唤醒的是
消费线程,消费时应该唤醒的是生产线程。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值