很简单的例子:读写锁测试并发。按照理论,写的时候是不能读的,但是运行结果中会看到读在写的中间,把线程睡眠打开可以达到写完再并发读,这是为什么呢?求解答! 下面是demo
package com.example.studyjuc;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class MyReentrantReadWriteLocK {
public static void main(String[] args) {
MyCache myCache = new MyCache();
for (int i = 1; i <= 50; i++) {
final String j = String.valueOf(i);
new Thread(()->{
myCache.put(j,j);
}).start();
}
for (int i = 1; i <= 5; i++) {
final String j = String.valueOf(i);
new Thread(()->{
myCache.get(j);
}).start();
}
while (Thread.activeCount()>2){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.activeCount());
}
}
}
class MyCache{
//volatile 关键字保证对其他线程可见
volatile Map<String,String> map = new HashMap<>();
private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();
public void get(String key){
readLock.lock();
try {
System.out.println("读-开始->key->"+key+"->"+map.get(key));
map.get(key);
//Thread.sleep(1000);
System.out.println("读-完成->key->"+key+"->"+map.get(key));
}catch (Exception e){
}finally {
readLock.unlock();
}
}
public void put(String key,String value){
writeLock.lock();
try {
System.out.println("写-开始->"+key);
//Thread.sleep(1000);
map.put(key,value);
System.out.println("写-完成->"+key);
}catch (Exception e){
}finally {
writeLock.unlock();
}
}
}
运行结果: