ReentrantReadWriteLock()
写锁是线程独享,同一时间只能有一个线程操作
读锁是线程共享:同一时间可以有多个线程操作
/**
* Created by Last on 2020/7/28.
* 读写锁
*/
public class D {
public static void main(String[] args) {
MyCacheLock myCacheLock = new MyCacheLock();
for (int i = 1; i < 5; i++) {
final int temp = i;
new Thread(()->{
myCacheLock.put(temp+"=","");
},String.valueOf(i)).start();
}
for (int i = 1; i < 5; i++) {
final int temp = i;
new Thread(()->{
myCacheLock.get(temp+"=");
},String.valueOf(i)).start();
}
}
}
class MyCacheLock {
private volatile Map<String, Object> map = new HashMap<>();
//普通Lock锁
private Lock lock = new ReentrantLock();
//读写锁 也叫独享所和共享锁
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void put(String key, Object obj) {
//独享写入锁加锁
readWriteLock.writeLock().lock();
try {
System.out.println("写入" + key);
map.put(key, obj);
System.out.println(key + "写入完成");
} catch (Exception e) {
e.printStackTrace();
} finally {
//独享写入锁解锁
readWriteLock.writeLock().unlock();
}
}
public void get(String key) {
//共享读取锁加锁
readWriteLock.readLock().lock();
try {
System.out.println("读取" + key);
map.get(key);
System.out.println(key + "读取成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
//共享读取锁解锁
readWriteLock.readLock().unlock();
}
}
}