读写锁
读写锁
为什么?
在高并发的场景下,我们写入数据时候可能被其他线程加塞,其他线程就读到了脏数据。
写 操作必须保持一致性,在我们写的时候,不允许其他线程来读。
是什么?
ReentrantReadWriteLock
使用读写锁实现一个缓存
public class juc2 {
public static void main(String[] args) {
MyCache myCache = new MyCache();
for (int i = 0; i < 5; i++) {
int finalI = i;
new Thread(() -> myCache.put(String.valueOf(finalI), finalI)).start();
}
for (int i = 0; i < 5; i++) {
int finalI = i;
new Thread(() -> myCache.get(String.valueOf(finalI))).start();
}
}
}
//缓存类
class MyCache {
private volatile Map<String, Object> mapCache = new HashMap<>();
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//存入缓存的操作
public void put(String key, Object value) {
try {
lock.writeLock().lock();
System.out.println(Thread.currentThread().getName() + "\t正在写入缓存" + "\tkey:" + key + "\tvalue" + value);
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
mapCache.put(key, value); //put操作不是原子的哦
System.out.println(Thread.currentThread().getName() + "\t写入完成");
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.writeLock().unlock();
}
}
//读取缓存中的值
public void get(String key) {
try {
lock.readLock().lock();
System.out.println(Thread.currentThread().getName() + "读取数据");
System.out.println(Thread.currentThread().getName() + "读取完成" + mapCache.get(key));
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.readLock().unlock();
}
}
public void clear(){
mapCache.clear();
}
} ReentrantReadWriteLock 中有两个内部类 wirteLock 、
查看4道真题和解析

