读写锁(ReentrantReadWriteLock)
重点: 1、读锁共享 2、写锁互斥 3、读写锁互斥 锁降级 :将写锁降级为读锁。(先获取写锁,再获取读锁,再释放写锁,最后释放读锁) 造成锁降级的原因:出于性能考虑,一般情况下,都将锁定的动作,精确到具体的语句块,在两个锁的语句块之间,有可能线程的交替执行,造成线程安全问题。 解决的方法: 1、将锁的范围扩大。 2、使用锁降级。 为什么需要锁降级: 伪代码: w.lock();//写锁 writeSomeDate();//修改某些数据 w.unlock();//释放写锁 r.lock();//读锁 readSomeDate();//获取某个数据 r.unlock();//释放读锁 此时,获取数据的时候,就有线程安全问题。 修改后的代码为: w.lock();//写锁 writeSomeDate();//修改某些数据 r.lock();//读锁 w.unlock();//释放写锁 readSomeDate();//获取某个数据 r.unlock();//释放读锁 将读锁的锁定动作,放入到写锁的释放之前,就可以将锁降级为读锁。 来源: https://www.cnblogs.com/chen--biao/p/11366952.html