读写锁的使用ReadWriteLock

接口 ReadWriteLock

实现类为java.util.concurrent.locks下的 ReentrantReadWriteLock

demo

class MyCache{
    
    private volatile Map<String, Object> map =new HashMap<String, Object>();
    ReadWriteLock readWriteLock =new ReentrantReadWriteLock();
    
    public void put(String key,Object value) {
        readWriteLock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"进行写操作开始");
        //让线程暂停一下
        try {
            TimeUnit.SECONDS.sleep(2);
            map.put(key, value);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
        
        System.out.println(Thread.currentThread().getName()+"写操作结束");
        
        
    }
    
    public void read(String key) {
        readWriteLock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"进行读操作开始");
        try {
            TimeUnit.SECONDS.sleep(2);
            Object object = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t进行读操作结束"+object);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
        
    }
    
}

/*
 * 多线程同时读一个资源类没有任何问题,所以为了满足并发量,读取共享资源应该可以同时进行。
 * 但是
 * 如果有有一个线程想去写共享资源,就不应该再有其它线程可以对该资源进行读或者写
 * 使用ReadWriteLock
 * 小结:
 *     读-读能共享
 *     读-写不能共享
 *     写-写不能共享
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        
        MyCache myCache = new MyCache();
        
        for (int i = 1; i <= 4; i++) {
            
            final Integer tempInt= i;
            new Thread(() -> {
                    myCache.put(String.valueOf(tempInt), tempInt+"");
                
            }, String.valueOf(i)).start();
        }
        
        for (int i = 1; i <= 4; i++) {
            
            final Integer tempInt= i;
            new Thread(() -> {
                myCache.read(String.valueOf(tempInt));
                
            }, String.valueOf(i)).start();
        }
        
    }
}

猜你喜欢

转载自www.cnblogs.com/fengyangcai/p/12903489.html