代码例子:写锁可以降级为读锁,读锁不能降级为写锁
public class ReadWriteLockDemo { public static void main(String[] args) { ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); //读锁 ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock(); //写锁 ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock(); //2.获取写锁 writeLock.lock(); System.out.println("---------write"); //1.获取读锁 readLock.lock(); System.out.println("---------read"); } }
public class ReadWriteLockDemo { public static void main(String[] args) { ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); //读锁 ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock(); //写锁 ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock(); //1.获取读锁 readLock.lock(); System.out.println("---------read"); //2.获取写锁 writeLock.lock(); System.out.println("---------write"); } }