private static final Semaphore lock = new Semaphore(Integer.MAX_VALUE, true);
public void doReadLocked() throws InterruptedException {
// 'Read' lock only acquires one permit, but since there are A LOT,
// many of them can run at once.
lock.acquire();
try {
// Do your stuff in here...
} finally {
// Make sure you release afterwards.
lock.release();
}
}
public void doWriteLocked() throws InterruptedException {
// 'Write' lock demands ALL the permits. Since fairness is set, this
// will 'take priority' over other waiting 'read'ers waiting to acquire
// permits.
lock.acquire(Integer.MAX_VALUE);
try {
// Do your stuff in here...
} finally {
// Make sure you release afterwards.
lock.release(Integer.MAX_VALUE);
}
}
1条答案
按热度按时间iyfjxgzm1#
而不是直接用
ReadWriteLock
,最简单的内置方法可能是Semaphore
,这确实支持公平。创造公平Semaphore
,具有(实际上)无限数量的permis
应该足够: