- 读写锁概念
- 读写锁的原理 就是 数据库上的排他锁 和 共享锁
- 锁升级的原理
- 代码实例展示
package com.pengshi.ThreadTest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class WRLock {
private volatile Map<String, String> map = new HashMap<>();
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void put(String str, String str1) {
readWriteLock.writeLock().lock();
try {
System.out.println("进行写操作" + Thread.currentThread().getName());
Thread.sleep(1000);
map.put(str, str1);
System.out.println("写操作完毕" + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}
public String get (String key) {
readWriteLock.readLock().lock();
try {
System.out.println("进行读操作" + Thread.currentThread().getName());
Thread.sleep(1000);
String str = map.get(key);
System.out.println("读操作完毕" + Thread.currentThread().getName() + "数据是" + str);
return str;
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
return null;
}
}
public class WriteAndReadLockTest {
public static void main(String[] args) {
WRLock test = new WRLock();
for (int i = 0; i < 5; ++i) {
String num = i + "";
new Thread(() -> {
test.put(num, "pc牛逼");
}, String.valueOf(i)).start();
}
for (int i = 0; i < 5; ++i) {
String num = i + "";
new Thread(() -> {
test.get(num);
}, String.valueOf(i)).start();
}
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
readWriteLock.writeLock().lock();
System.out.println("写操作");
readWriteLock.readLock().lock();
System.out.println("读操作");
readWriteLock.readLock().unlock();
readWriteLock.writeLock().unlock();
}
}