通过代码发现锁降级以后发现还是持有写锁
在 readLock.lock(); 后
writeLock.isHeldByCurrentThread() 仍然为true
private static void writeDowngrading() {
writeLock.lock();
try {
System.out.println(Thread.currentThread().getName() + "得到了写锁,正在写入");
Thread.sleep(1000);
readLock.lock();
System.out.println("在不释放写锁的情况下,直接获取读锁,成功降级");
// 打印为true:说明降级后仍持有写锁
System.out.println(writeLock.isHeldByCurrentThread());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
readLock.unlock();
System.out.println(Thread.currentThread().getName() + "释放写锁");
writeLock.unlock();
// 打印为false:不再持有写锁
System.out.println(writeLock.isHeldByCurrentThread());
}
}
锁降级以后仍然持有写锁,那么降级的意义何在呢?岂不是其他想要读的线程依然要阻塞,为什么在设计的时候没有在降级的时候直接把写锁释放呢?
锁的降级和我们自己 获取写锁 --> 释放写锁 --> 获取读锁 --> 读取数据 --> 释放读锁
有什么区别呢?