ReadWriteLock 是 JDK 中的读写锁接口
ReentrantReadWriteLock 是 ReadWriteLock 的一种实现
读写锁非常适合读多写少的场景。读写锁与互斥锁的一个重要区别是读写锁允许多个线程同时读共享变量,这是读写锁在读多写少的情况下性能较高的原因。
读写锁的原则:
升级与降级:
读写锁的应用示例:
package constxiong.interview;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 测试 读写锁
* @author ConstXiong
* @date 2019-12-19 10:40:45
*/
public class TestReadWriteLock {
final static ReadWriteLock rwLock = new ReentrantReadWriteLock();
final static Lock readLock = rwLock.readLock();//读锁
final static Lock writeLock = rwLock.writeLock();//写锁
static int count = 0;
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":" + get());
}).start();
}
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " add");
add();
}).start();
}
}
private static int get() {
readLock.lock();
try {
return count;
} finally {
readLock.unlock();
}
}
private static void add() {
writeLock.lock();
try {
count++;
} finally {
writeLock.unlock();
}
}
}
ConstXiong 备案号:苏ICP备16009629号-3