JAVA小学生——java锁之读写锁,
分享于 点击 14568 次 点评:76
JAVA小学生——java锁之读写锁,
1. 什么是独占锁?共享锁?
image.png2. 读写锁的作用
image.png3. 手写读写分离缓存
3.1 代码实现
public class WriteAndReadCacheDemo {
/**
* 加入volatile 线程间保证【可见性】
*/
private volatile Map<String, Object> map = new HashMap<>();
/**
* 使用ReentrantReadWriteLock 读写锁,防止并发写入的情况
*/
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public void put(String key, Object obj) {
lock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "\t 正在写入");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
map.put(key, obj);
System.out.println(Thread.currentThread().getName() + "\t 正在完成");
} finally {
lock.writeLock().unlock();
}
}
public void get(String key) {
lock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "\t 正在获取");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Object result = map.get(key);
System.out.println(Thread.currentThread().getName() + "\t 获取完成,value=" + result);
} finally {
lock.readLock().unlock();
}
}
public static void main(String[] args) {
WriteAndReadCacheDemo myCache = new WriteAndReadCacheDemo();
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(() -> {
String key = "key" + temp;
myCache.put(key, temp);
}, "T" + i).start();
}
for (int i = 0; i < 5; i++) {
final int temp = i;
new Thread(() -> {
String key = "key" + temp;
myCache.get(key);
}, "T" + i).start();
}
}
}
3.2 效果比对
读写分离效果转载于:https://www.jianshu.com/p/927e7d817e84
相关文章
- 暂无相关文章
用户点评