所谓的锁降级是指写锁降级为读锁,如果当前线程拥有某个对象的写锁,再获取该对象的读锁,随后释放写锁的过程。该过程与获取写锁之后将其释放,最后在获取读锁的过程相比,前者能够感知到自己对该变量做的相关操作,因为释放写锁后,如果其它线程T直接获取该对象的写锁,则会对该对象的值进行修改,本线程S再读取该值时,会获取到T修改后的值,而不能获取S修改后的值。
public class Cache {
static Map map = new HashMap();
static ReentrantReadWriteLock rw1 = new ReentrantReadWriteLock();
static Lock r = rw1.readLock();
static Lock w = rw1.writeLock();
public static final Object get(String key){
r.lock();
try{
return map.get(key);
}finally {
r.unlock();
}
}
public static void main(String[] args){
Thread t1 = new Thread(new Runnable() {
public void run() {
put("A",123);
}
},"t1");
Thread t2 = new Thread(new Runnable() {
public void run() {
put("A",456);
}
},"t2");
Thread t3 = new Thread(new Runnable() {
public void run() {
put("A",789);
}
},"t3");
t1.start();
t2.start();
t3.start();
}
public static final void put(String key,Object value){
w.lock();
try{
map.put(key,value);
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
finally {
r.lock();
System.out.println(Thread.currentThread().getName()+" "+map.get("A"));
w.unlock();
r.unlock();
}
}
public static final void clear(){
w.lock();
try{
map.clear();
}finally {
w.unlock();
}
}
t2 456
t1 123
t3 789
finally {
w.unlock();
r.lock();
System.out.println(Thread.currentThread().getName()+" "+map.get("A"));
r.unlock();
}
t2 789
t1 789
t3 789