JUC之读写锁

* 读写锁:
* 读读可以共存
* 读写不能共存
* 写写不能共存
*
* 独占锁(写锁)
* 共享锁(读锁)
*/
public class ReadWriteLockTest {
public static void main(String[] args) {
MyCache myCache = new MyCache();

for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(()->{
myCache.put(temp+"",temp+"");
},String.valueOf(i)).start();
}
for (int i = 1; i <= 5; i++) {
final int temp = i;
new Thread(()->{
myCache.get(temp+"");
},String.valueOf(i)).start();
}
}
}

/**
* 自定义缓存
*/
class MyCache{
private volatile Map<String,Object> map = new HashMap<>();

private ReadWriteLock 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");
} catch (Exception e) {
e.printStackTrace();
} 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");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}
}
posted @ 2020-11-18 00:18  ITYW  阅读(122)  评论(0编辑  收藏  举报