系列十、ReentrantReadWriteLock
一、概述
ReentrantReadWriteLock是ReadWriteLock的一个子类,具有读锁和写锁的双重功能,通常用于做缓存。
二、案例代码
2.1、ReentrantReadWriteLockCache
/**
* @Author : 一叶浮萍归大海
* @Date: 2023/11/20 17:57
* @Description: 使用ReentrantReadWriteLock实现缓存的功能
*/
public class ReentrantReadWriteLockCache {
private volatile Map<String, Object> map = new HashMap<>();
private ReadWriteLock rwLock = new ReentrantReadWriteLock();
/**
* 写数据
* @param key
* @param value
*/
public void put(String key, Object value) {
rwLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "\t正在写" + key);
// 线程休眠,单位:毫秒
try {TimeUnit.MILLISECONDS.sleep(300);} catch (Exception e) {e.printStackTrace();}
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "\t写完了" + key);
System.out.println();
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.writeLock().unlock();
}
}
/**
* 读数据
* @param key
* @return
*/
public Object get(String key) {
rwLock.readLock().lock();
Object result = null;
try {
System.out.println(Thread.currentThread().getName() + "\t正在读" + key);
// 线程休眠,单位:毫秒
try {TimeUnit.MILLISECONDS.sleep(300);} catch (Exception e) {e.printStackTrace();}
result = map.get(key);
System.out.println(Thread.currentThread().getName() + "\t读完了" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.readLock().unlock();
}
return result;
}
}
2.2、ReentrantReadWriteLockMainApp
/**
* @Author : 一叶浮萍归大海
* @Date: 2023/11/20 18:00
* @Description:
*/
public class ReentrantReadWriteLockMainApp {
public static void main(String[] args) {
ReentrantReadWriteLockCache cache = new ReentrantReadWriteLockCache();
for (int i = 1; i <= 5; i++) {
final int number = i;
new Thread(() -> {
try {
cache.put(String.valueOf(number),number);
} catch (Exception e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
for (int i = 1; i <= 5; i++) {
final int number = i;
new Thread(() -> {
try {
cache.get(String.valueOf(number));
} catch (Exception e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}