1、锁降级:写线程获取写入锁后可以获取读取锁,然后释放写入锁,这样就从写入锁变成了读取锁,从而实现锁降级的特性
2、锁降级之后,写锁并不会直接降级成读锁,不会随着读锁的释放而释放,因此需要显式地释放写锁
3、锁降级的应用场景:用于对数据比较敏感,需要在对数据修改之后,获取到修改后的值,并进行接下来的其他操作
public class LockDegrade {
public static void main(String[] args) {
ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
Lock readLock = reentrantReadWriteLock.readLock();
Lock writeLock = reentrantReadWriteLock.writeLock();
writeLock.lock();
readLock.lock();
writeLock.unlock();
readLock.unlock();
System.out.println("程序运行结束");
}
}
# 控制台执行结果:
程序运行结束
public class LockDegradeDemo {
private int i = 0;
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
Lock readLock = readWriteLock.readLock();
Lock writeLock = readWriteLock.writeLock();
public void doSomething() {
// 打开写锁
writeLock.lock();
try {
i++;
// 若i++是1个敏感操作
// 操作完后,在写锁还没关闭前,开启读锁
readLock.lock();
}finally {
// 关闭写锁
writeLock.unlock();
}
// 执行其他操作
try {
//模拟其他复杂的操作
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 之后其他线程操作,最后关系读锁
try {
if (i == 1) {
System.out.println("i的值是======》1");
} else {
System.out.println("i的值是"+i);
}
} finally {
readLock.unlock();
}
}
public static void main(String[] args) {
LockDegradeDemo lockDegradeDemo = new LockDegradeDemo();
for (int i = 0; i < 4; i++) {
new Thread(()->{
lockDegradeDemo.doSomething();
}).start();
}
}
}
# 控制台结果:
i的值是======》1
i的值是2
i的值是3
i的值是4