在 Java 中,ReadWriteLock 接口的实现类ReentrantReadWriteLock 类
提供了一种允许多个线程同时读取某一资源但只允许一个线程写的锁定机制。这种机制可以提高并发性能,特别是在读操作远多于写操作的场景下。
特性:
- 可重入;
- 不存在两个线程同时持有写锁,或一个持有读锁一个持有写锁;
- 只存在写锁独占,或都是持有读锁;
- 写锁也叫排它锁,读锁也叫共享锁;
- 支持锁降级,锁降级(Lock Downgrading)是指在持有写锁的情况下,可以获取读锁,然后释放写锁,以便在读取共享资源时仍保持一定的同步。
锁降级例子:
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;public class ReadWriteLockExample {private int value = 0;private final ReadWriteLock lock = new ReentrantReadWriteLock();public void writeAndRead() {lock.writeLock().lock(); // 获取写锁try {value++;System.out.println("Written value: " + value);lock.readLock().lock(); // 获取读锁} finally {lock.writeLock().unlock(); // 释放写锁, 之后其他线程就可以获取读锁了}try {Thread.sleep(10000);System.out.println("Read value after write: " + value);} catch (InterruptedException e) {throw new RuntimeException(e);} finally {lock.readLock().unlock(); // 释放读锁}}public int read() {lock.readLock().lock(); // 获取读锁try {System.out.println("Read value: " + value);return value;} finally {lock.readLock().unlock(); // 释放读锁}}public static void main(String[] args) throws InterruptedException {ReadWriteLockExample example = new ReadWriteLockExample();// Writer threadThread writerThread = new Thread(() -> {example.writeAndRead();});// Reader threadThread readerThread = new Thread(() -> {example.read();});writerThread.start();Thread.sleep(2000);readerThread.start();}
}
输出: