java conditionobject_Java多线程框架源码阅读之---AQS的ConditionObject

前置文章为https://segmentfault.com/a/11...,如果不了解AQS的基本lock和unlock实现机制,建议先看一下这个文章。

Condition类似于wait和notify,notifyAll,常用于实现生产者消费者。以下代码是一个用ReentrantLock的condition做的一个生产者消费者例子。

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

class BoundedBuffer {

final Lock lock = new ReentrantLock();

// condition 依赖于 lock 来产生

final Condition notFull = lock.newCondition();

final Condition notEmpty = lock.newCondition();

final Object[] items = new Object[100];

int putptr, takeptr, count;

// 生产

public void put(Object x) throws InterruptedException {

lock.lock();

try {

while (count == items.length)

notFull.await(); // 队列已满,等待,直到 not full 才能继续生产

items[putptr] = x;

if (++putptr == items.length) putptr = 0;

++count;

notEmpty.signal(); // 生产成功,队列已经 not empty 了,发个通知出去

} finally {

lock.unlock();

}

}

// 消费

public Object take() throws InterruptedException {

lock.lock();

try {

while (count == 0)

notEmpty.await(); // 队列为空,等待,直到队列 not empty,才能继续消费

Object x = items[takeptr];

if (++takeptr == items.length) takeptr = 0;

--count;

notFull.signal(); // 被我消费掉一个,队列 not full 了,发个通知出去

return x;

} finally {

lock.unlock();

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值