锁降级--防止线程安全问题

package com.demo.lock.writer.to.read;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 
 * 锁降级:是将写锁降级为读锁
 * 即为:在获取到写锁后,接着又获取到读锁后,此时再释放写锁
 * 
 * @author Administrator
 *
 */
public class WriteToReadLockDemo {

    private volatile boolean isUpdate;
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private Map<String, Object> map = new HashMap<String, Object>();
    private Lock rLock = rwLock.readLock();
    private Lock wLock = rwLock.writeLock();

    public void method() {
        /*
         * 不同线程之间,读写锁是互斥的,同一个线程锁是可重入的
         * 为了当有线程获取了写锁时,其它线程想获取读锁,也会等待写锁释放时,才可以进行
         * 其实质就是为了当有线程在修改isUpdate值时,此时不能去读取isUpdate值
         */
        rLock.lock();
        if (isUpdate) {//添加volatile:为了保证当前线程修改了 isUpdate值对其它线程是可见的,
            rLock.unlock();//释放读锁
            /*
             * 步骤 1 2 3 即为锁降级
             */
            wLock.lock();//获取写锁 1
            map.put("xxx", "xxxx");
            rLock.lock();//获取读锁(防止还没有将map设置的值取出--步骤4,又有其它线程获取到写锁,对map进行重新赋值) 2
            wLock.unlock();//释放写锁 3
        }
        Object object = map.get("xxx");//4
        System.out.println(object);
        rLock.unlock();
    }
    
}

 

posted @ 2018-12-06 19:55  scwyfy  阅读(491)  评论(0编辑  收藏  举报