ReadWriteLock
翻译:
读取写入锁
解释:
-
在写入与读取的时候,会被其他线程插队,对于读取线程是不要紧的,但是对于读取线程,就会出现很多的问题
-
在以前我们可以synchronized ,ReetrentLock锁住
-
现在使用更加细腻的 ReadWriteLock
用法
不加锁的情况下
public class ReadAndWriteLockTest {
public static void main(String[] args) {
MyCache myCache = new MyCache();
for (int i = 0; i < 5; i++) {
int finalI = i;
new Thread(() ->{
myCache.pushItem(String.valueOf(finalI), finalI);
},String.valueOf(i)).start();
}
for (int i = 0; i < 5; i++) {
int finalI = i;
new Thread(() ->{
myCache.getItem(String.valueOf(finalI));
},String.valueOf(i)).start();
}
}
}
class MyCache{
private Map<String ,Integer> map = new HashMap<>();
public void pushItem(String key,Integer value){
System.out.println(Thread.currentThread().getName() + "准备写入");
map.put(key,value);
System.out.println(Thread.currentThread().getName() + "写入成功");
}
public void getItem(String key){
System.out.println(Thread.currentThread().getName() + "准备读取");
map.get(key);
System.out.println(Thread.currentThread().getName() + "读取成功");
}
}
会出现写入的时候,其他线程插队的情况
加入读写锁ReadWriteLock
class MyCache{
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private Map<String ,Integer> map = new HashMap<>();
public void pushItem(String key,Integer value){
readWriteLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "准备写入");
map.put(key,value);
System.out.println(Thread.currentThread().getName() + "写入成功");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
readWriteLock.writeLock().unlock();
}
}
public void getItem(String key){
readWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "准备读取");
map.get(key);
System.out.println(Thread.currentThread().getName() + "读取成功");
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
readWriteLock.readLock().unlock();
}
}
}
- ReadWriteLock是接口,实现类是 ReetrantReadWirteLock,所以接口与实现类啦
- 通过上述的内容,就可以实现了在写入的时候,没有新的线程的插队
- 但是为什么是所有的 写入数据 先执行,这是我所不知道的