1、在某些情况下,当内部锁非常不灵活时,显式锁就可以派上用场。内部条件队列有一些缺陷,每个内部锁只能有一个与之相关联的条件队列。
2、使用显式的Lock和Condition的实现类提供了一个比内部锁和条件队列更加灵活的选择。一个Condition和一个单独的Lock相关联,就像条件队列和单独的内部锁相关联一样。每个锁可以有多个等待集、中断性选择、基于时限、公平性选择等。
public interface Condition{
void await() throws InterruptedException;//相当于wait
boolean await(long time,TimeUnit unit) throws InterruptedException;
long awaitNanos(long nanosTimeout) throws InterruptedException;
void awaitUninterruptibly();
boolean awaitUntil(Date deadline) throws InterruptedException;
void signal();//相当于notify
void signalAll();//相当于notifyall
}
调用与Condition相关联的Lock的Lock.newCondition方法,可创建一个Condition.
3、有限缓存操作
@ThreadSafe
public class ConditionBoundedBuffer<T>{
protected final Lock lock=new ReentrantLock();
private final Condition notFull=lock.newCondition();
private final Condition notEmpty=lock.newCondition();
@GuardBy("lock");
private final T[] items=(T[]) new Object[BUFFER_SIZE];
@GuardBy("lock") private int tail,head,count;
public void put(T x) throws InterruptedExceptoin{
lock.lock();
try{
while (count=items.lentgh)
notFull.await();
items[tail]=x;
if (++tail=items.length)
tail=0;
++count;
notEmpty.signal();
}
finally{lock.unlock();
}
}
public T take() throws InterruptedException{
lock.lock();
try{
while (count=items.lentgh)
notEmpty.await();
T x=items[head];
items[head]=null;
if (++head=items.length)
head=0;
--count;
notFull.signal();
return x;
}
finally{lock.unlock();
}
}
}