一、案例代码
public class ReadLockAndWriteLockTest {
//存储数据
private volatile Map<String,String> map=new HashMap<>();
//读写锁
private ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
//写入锁
private WriteLock writeLock=readWriteLock.writeLock();
//读取锁
private ReadLock readLock=readWriteLock.readLock();
//添加元素
public void put(String key,String value){
try {
writeLock.lock();
System.out.println("写入开始数据开始,key:"+key+",value:"+value);
map.put(key,value);
System.out.println("写入开始数据结束,key:"+key+",value:"+value);
} finally {
writeLock.unlock();
}
}
//读取元素
public String get(String key){
try {
readLock.lock();
System.out.println("读数据开始,key:"+key);
String value = map.get(key);
System.out.println("读数据开始,key:"+key+",value:"+value);
return value;
} catch (Exception e) {
return null;
} finally {
readLock.unlock();
}
}
public static void main(String[] args) {
ReadLockAndWriteLockTest readLockAndWriteLockTest=new ReadLockAndWriteLockTest();
//写线程
Thread writeThread=new Thread(()->{
for (int i = 0; i < 10; i++) {
readLockAndWriteLockTest.put(i+"",i+"");
}
});
writeThread.start();
//读线程
Thread readThread=new Thread(()->{
for (int i = 0; i < 10; i++) {
readLockAndWriteLockTest.get(i+"");
}
});
readThread.start();
}
}
二、测试结果
未加锁时:
加读写锁以后: