package com.zhangye;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class MyCache{
private volatile Map<String,Object> map = new HashMap<>();
private ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
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 写入完成:");
} catch (Exception e) {
e.printStackTrace();
} finally{
rwlock.writeLock().unlock();
}
}
public void get(String key){
rwlock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+"\t 正在读取:");
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
Object obj = map.get(key);
System.out.println(Thread.currentThread().getName()+"\t 写入完成:"+obj);
} catch (Exception e) {
e.printStackTrace();
}finally{
rwlock.readLock().unlock();
}
}
}
public class ReadWriteLockTest {
public static void main(String[] args) {
MyCache myCache = new MyCache();
for (int i = 0; i < 5; i++) {
final int tempInt = i;
new Thread(()->{
myCache.put(tempInt+"", tempInt);
},String.valueOf(i)).start();
}
for (int i = 0; i < 5; i++) {
final int tempInt = i;
new Thread(()->{
myCache.get(tempInt+"");
},String.valueOf(i)).start();
}
}
}
打印结果
1 正在写入:1
1 写入完成:
0 正在写入:0
0 写入完成:
2 正在写入:2
2 写入完成:
3 正在写入:3
3 写入完成:
4 正在写入:4
4 写入完成:
0 正在读取:
1 正在读取:
2 正在读取:
3 正在读取:
4 正在读取:
2 写入完成:2
1 写入完成:1
0 写入完成:0
4 写入完成:4
3 写入完成:3