package threads;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class CacheDemo {
private static ReadWriteLock rwl = new ReentrantReadWriteLock();
private static Map<String, Object> map = new HashMap<String, Object>();
public static void main(String[] args) {
/*for(int i = 0; i < 5; i++){
map.put(String.valueOf(i), i);
}*/
for(int i = 0; i < 10; i++){
final int value = i;
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
System.out.println(Thread.currentThread().getName() + " is getting data " + getData(String.valueOf(10)));
}
}
}).start();
}
}
public static Object getData(String key){
Object value = null;
try{
rwl.readLock().lock();
value = map.get(key);
if(value == null){
System.out.println(Thread.currentThread().getName() + " hello world");
rwl.readLock().unlock();
rwl.writeLock().lock();//会不会有多个线程一同加锁的情况?就是说多个线程同时运行到此句
try{
if(value == null){ //验证alue是否被其他线程赋值
System.out.println(Thread.currentThread().getName() + " welcome");
value = "aaaa + " + key;//实际上可以从数据库中查询然后赋值
map.put(key, value);
}
}finally{
rwl.readLock().lock();
rwl.writeLock().unlock();
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
rwl.readLock().unlock();
}
return value;
}
}
下面是一次运行的结果中的部分,预期是不会有两次welcom的语句出现,可是出现了三次,请帮忙调试下
Thread-2 hello world
Thread-1 hello world
Thread-0 hello world
Thread-2 welcome
Thread-2 is getting data aaaa + 10
Thread-1 welcome
Thread-1 is getting data aaaa + 10
Thread-1 is getting data aaaa + 10
Thread-1 is getting data aaaa + 10
Thread-3 is getting data aaaa + 10
Thread-0 welcome
Thread-0 is getting data aaaa + 10
Thread-0 is getting data aaaa + 10
Thread-0 is getting data aaaa + 10
Thread-0 is getting data aaaa + 10
Thread-9 is getting data aaaa + 10
|