java再复习——使用JDK1.5新特性优化生产者消费者

传统的生产者消费者代码有一个问题:

就是在notifyAll的时候会唤醒锁池中所有等待的线程,包括消费者线程和生产者线程,但是我们只知道,我们生产完之后值想唤醒消费者线程,我们消费完之后只想唤醒生产者线程,这样唤醒无用线程,既增加多余的判断,又影响性能。java在JDK1.5以后就提供了比较好的工具,把wait,notify,notifyAll方法封装成了一个Condition对象,可供我们操作。

代码示例:

/**
 * 资源
 * @author PC
 *
 */
class Resource {
	int count = 0;
	boolean isHas = false;
	ReentrantLock reentranlock = new ReentrantLock();
	Condition conditionProducer = reentranlock.newCondition();
	Condition conditionConsumer = reentranlock.newCondition();
	
	public void product() {
		reentranlock.lock();
		try {
			while(isHas){
					conditionProducer.await(); //为了方便阅读 ,异常直接抛出了。
			}
			System.out.println(Thread.currentThread().getName() + "..生成了商品【"+(++count)+"】----");
			isHas = true;
			conditionConsumer.signalAll();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			reentranlock.unlock();
		}
	}
	
	public  void consume(){
		reentranlock.lock();
		try {
			while(!isHas){
				conditionConsumer.await();
			}
			System.out.println(Thread.currentThread().getName() + "..消费了商品【"+count+"】");
			isHas = false;
			conditionProducer.signalAll();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			reentranlock.unlock();
		}
	}
}

/**
 * 生产者
 * @author PC
 *
 */
class Producer implements Runnable{
	
	Resource resource;
	
	public Producer(Resource resource){
		this.resource = resource;
	}

	public void run() {
		while (true) {
			resource.product();
		}
	}
	
}

/**
 * 消费者
 * @author PC
 *
 */
class Consumer implements Runnable{
	
	Resource resource;
	
	public Consumer(Resource resource){
		this.resource = resource;
	}

	public void run() {
		while (true) {
			resource.consume();
		}
	}
	
}

妥妥的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值