读写锁--DEMO

package com.demo.read.write.lock;

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 ReadWriteLockDemo {

    private Map<String, Object> map = new HashMap<String, Object>();
    
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();
    
    private Lock rLock = rwLock.readLock();
    
    private Lock wLock = rwLock.writeLock();
    
    public void put(String key, Object value) throws InterruptedException {
        wLock.lock();
        System.out.println(Thread.currentThread().getName() + " 写操作执行了。。。");
        Thread.sleep(1000);
        try {
            map.put(key, value);
        } finally {
            System.out.println(Thread.currentThread().getName() + " 写操作执行完成了。。。");
            wLock.unlock();
        }
    }
    
    public Object get(String key) throws InterruptedException {
        rLock.lock();
        System.out.println(Thread.currentThread().getName() + " 读操作执行了。。。");
        Thread.sleep(1000);
        try {
            return map.get(key);
        } finally {
            System.out.println(Thread.currentThread().getName() + " 读操作执行完成了。。。");
            rLock.unlock();
        }
    }
    
}

 

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