JUC:读写锁

独占锁(写锁):一次只能被一个线程占有
共享锁(读锁):该锁可以被多个线程占有!

 

 测试代码

// 加锁操作: 读写锁
class MyCacheLock{
    private volatile Map<String, Object> map = new HashMap<>();
    //    读写锁
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    // 读 : 可以被多个线程同时读
    public void get(String key) {
        Lock readLock = this.lock.readLock();
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取结果:" + o);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }

    // 写 :应该是保证原子性 , 不应该被打扰
    public void put(String key, Object value) {
        Lock writeLock = this.lock.writeLock();
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }
}

测试结果:

 

 

posted @ 2020-03-06 20:31  alenblue\own  阅读(195)  评论(0编辑  收藏  举报