介绍
与synchronized类似,Lock中的为 await() , signal , signalAll()。await()将线程添加到对应的条件队列,signal是将对应的条件队列中等待时间最长的节点放入等待队列中,signalAll()是将条件队列中的所有节点放入等待队列中
使用
来简单使用下,实现一个阻塞队列
class BoundedBlockingQueue {
private final Lock lock = new ReentrantLock();
private final Condition empty = lock.newCondition();
private final Condition full = lock.newCondition();
private final int CAPACITY;
private Queue<Integer> q = new LinkedList<>();
public BoundedBlockingQueue(int capacity) {
this.CAPACITY = capacity;
}
public void enqueue(int element) throws InterruptedException {
lock.lock();
try{
while(q.size() == CAPACITY){
full.await();
}
q.offer(element);
empty.signalAll();
}finally {
lock.unlock();
}
}
public int dequeue() throws InterruptedException {
lock.lock();
try{
while(q.isEmpty()){
empty.await();
}
int res = q.poll();
full.signalAll();
return res;
}finally {
lock.unlock();
}
}
public int size() {
lock.lock();
try{
return q.size();
}finally {
lock.unlock();
}
}
}