读写锁
Posted hpdblogs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读写锁相关的知识,希望对你有一定的参考价值。
读锁也叫共享锁
写锁也叫独享锁
读锁写锁都会造成死锁的问题
class MyCache{
private volatile Map<String,String> map = new HashMap<>();
private ReadWriteLock rwLock = new ReentrantReadWriteLock();
public void put(String key,String value){
rwLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName()
+" 准备写入数据"+key);
TimeUnit.MILLISECONDS.sleep(200);
map.put(key, value);
System.out.println(Thread.currentThread().getName()
+" 写入数据完成"+key);
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.writeLock().unlock();
}
}
public void get(String key){
rwLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()
+" 准备读取数据"+key);
TimeUnit.MILLISECONDS.sleep(200);
String value = map.get(key);
System.out.println(Thread.currentThread().getName()
+" 读取数据完成"+value);
} catch (Exception e) {
e.printStackTrace();
} finally {
rwLock.readLock().unlock();
}
}
}
public class ReadWriteLockDemo {
public static void main(String[] args) throws InterruptedException {
MyCache myCache = new MyCache();
for (int i = 1; i <=5 ; i++) {
String key = String.valueOf(i);
new Thread(()->{
myCache.put(key, UUID.randomUUID().toString().substring(0,8));
},String.valueOf(i)).start();
}
TimeUnit.SECONDS.sleep(2);
for (int i = 1; i <=5 ; i++) {
String key = String.valueOf(i);
new Thread(()->{
myCache.get(key);
},String.valueOf(i)).start();
}
}
}
以上是关于读写锁的主要内容,如果未能解决你的问题,请参考以下文章