一、ReadWriteLock介绍
来自JDK1.8 api文档
ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive。
翻译:
ReadWriteLock维护一对相关的锁,一个用于只读操作,一个用于写入。只要没有写,读锁可以由多个读线程同时持有。写锁是独占的。
二、不用ReadWriteLock的情况
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCache myCache = new MyCache();
//写入
for (int i = 0; i < 5; i++) {
final int temp=i;
new Thread(()->{
myCache.put(temp+"",temp+"");
}).start();
}
//读取
for (int i = 0; i < 5; i++) {
final int temp=i;
new Thread(()->{
myCache.get(temp+"");
}).start();
}
}
}
//自定义缓存
class MyCache{
private volatile Map<String,Object> map= new HashMap<>();
//存,写
public void put(String key, Object value){
System.out.println(Thread.currentThread().getName()+"写入"+key);
map.put(key, value);
System.out.println(Thread.currentThread().getName()+"写入OK"+key);
}
//取,读
public void get(String key){
System.out.println(Thread.currentThread().getName()+"读取"+key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"读取OK"+key);
}
}
这里我们可以发现,Thread3还没有写完成,Thread2就开始写入。
三、使用ReadWriteLock
/*
* 独占锁(写锁) 一次只能被一个线程占有
* 共享锁(读锁) 多个线程可以同时占有
* ReadWriteLock
* 读-读 可以共存
* 读-写 不能共存
* 写-写 不能共存
*/
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCache2 myCache = new MyCache2();
//写入
for (int i = 0; i < 5; i++) {
final int temp=i;
new Thread(()->{
myCache.put(temp+"",temp+"");
}).start();
}
//读取
for (int i = 0; i < 5; i++) {
final int temp=i;
new Thread(()->{
myCache.get(temp+"");
}).start();
}
}
}
//加锁的
class MyCache2{
private volatile Map<String,Object> map= new HashMap<>();
//读写锁:更加细粒度的控制
private ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
//存,写入的时候,只希望同时只有一个线程写
public void put(String key, Object value){
readWriteLock.writeLock().lock();
try{
System.out.println(Thread.currentThread().getName()+"写入"+key);
map.put(key, value);
System.out.println(Thread.currentThread().getName()+"写入OK"+key);
}finally{
readWriteLock.writeLock().unlock();
}
}
//取,读,所有人都可以读
public void get(String key){
readWriteLock.readLock().lock();
try{
System.out.println(Thread.currentThread().getName()+"读取"+key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName()+"读取OK"+key);
}finally{
readWriteLock.readLock().unlock();
}
}
}
写入与读取没有问题!