多个线程去同时读取一个共享资源类,为了并发性,同时读没有任何问题
但是如果有一个线程要去修改共享资源类,就不应该再有其他线程对资源类进行写和读的操作
读--读可共存
读--写不能共存
写--写不能共存
写:是原子性,不可分割
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCache myCache = new MyCache();
for (int i = 1; i <=5 ; i++) {
final int tempInt = i;
new Thread(()->{
myCache.put(tempInt+"",tempInt+"");
}, String.valueOf(i)).start();
}
for (int i = 1; i <=5 ; i++) {
final int tempInt = i;
new Thread(()->{
myCache.get(tempInt+"");
}, String.valueOf(i)).start();
}
}
}
/**
* 资源类
*/
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);
Thread.sleep(300);
map.put(key,value);
System.out.println(Thread.currentThread().getName()+"\t put正在完成");
}catch (Exception ex){
ex.printStackTrace();
}finally {
rwLock.writeLock().unlock();
}
}
public void get(String key){
//加读锁
rwLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+"\t 正在读取:"+key);
Thread.sleep(300);
Object result = map.get(key);
System.out.println(Thread.currentThread().getName()+"\t get正在完成:"+result);
}catch (Exception ex){
ex.printStackTrace();
}finally {
rwLock.readLock().unlock();
}
}
}
结果
1 正在写入:1
1 put正在完成
2 正在写入:2
2 put正在完成
3 正在写入:3
3 put正在完成
5 正在写入:5
5 put正在完成
4 正在写入:4
4 put正在完成
1 正在读取:1
2 正在读取:2
3 正在读取:3
4 正在读取:4
5 正在读取:5
2 get正在完成:2
4 get正在完成:4
5 get正在完成:5
1 get正在完成:1
3 get正在完成:3
网友评论