java.util.concurrent.locks.ReadWriteLock 是一个高级的线程锁,允许多个线程去读一个资源,但是同一时间只能有一个线程去写资源.
ReadWriteLock锁规则
Read Lock 如果没有写线程锁住ReadWriteLock对象,并且没有写线程请求写锁,此时多个读线程可以锁住该ReadWriteLock对象.
Write Lock 如果没有线程读或者写,这样同一时间一个线程可以锁住改线程锁.
ReadWriteLock实现
ReadWriteLock是一个接口. 实现是ReentrantReadWriteLock
ReadWriteLock样例代码
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
readWriteLock.readLock().lock();
// multiple readers can enter this section
// if not locked for writing, and not writers waiting
// to lock for writing.
readWriteLock.readLock().unlock();
readWriteLock.writeLock().lock();
// only one writer can enter this section,
// and only if no threads are currently reading.
readWriteLock.writeLock().unlock();