关于锁降级(ReentrantReadWriteLock)

锁降级:线程获取写锁后,在释放写锁之前获取读锁,然后再释放写锁,这样就实现了锁降级的特性。

注意:线程获取读锁后,写锁不会释放,需要显示的释放,在ReentrantReadWriteLock中,不存在锁的升级。

锁降级应用场景: 对于数据比较敏感, 需要在对数据修改以后, 获取到修改后的值, 并进行接下来的其它操作。

package xxx;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Demo {
    private volatile int i = 0;
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();

    void lockDegrade() {
        writeLock.lock();
        try {
            i++;
            readLock.lock();//未释放写锁之前获取读锁
        } finally {
            writeLock.unlock();
        }
        //Do something
        try {
            System.out.println(Thread.currentThread().getName()+" i:" + i);
        } finally {
            readLock.unlock();
        }
    }

    public static void main(String[] a) {
        Demo demo3 = new Demo();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                demo3.lockDegrade();
            }, "线程"+i).start();
        }
        /*输出:
            线程0 i:1
            线程1 i:2
            线程2 i:3
            线程3 i:4
            线程4 i:5
            线程5 i:6
            线程6 i:7
            线程7 i:8
            线程9 i:9
            线程8 i:10
             */
    }
}


 

你可能感兴趣的:(Java并发编程)