1 回答

TA貢獻1780條經驗 獲得超5個贊
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();
}
}
}
添加回答
舉報