编程语言
首页 > 编程语言> > Java 读写锁 ReadWriteLock

Java 读写锁 ReadWriteLock

作者:互联网

基本概念

维护了一对锁,read lock 可以由多个线程执行,只要没有作者那么write lock就是独家的

简单例子

package com.jie.rw;

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

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache=new MyCache();

        //写入
        for (int i = 1; i <= 5; i++) {
            final int temp=i;
            new Thread(()->{
                myCache.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }

        //读取
        for (int i = 1; i <= 5; i++) {
            final int temp=i;
            new Thread(()->{
                myCache.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}
class MyCache{
    private volatile Map<String,Object> map=new HashMap<>();
    //读写锁
    ReentrantReadWriteLock lock=  new ReentrantReadWriteLock();
    //模拟写
    public void put(String key,Object value){
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入完毕");
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.writeLock().unlock();
        }
    }
    //模拟读
    public void get(String key){
        lock.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            Object o=map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取完毕");
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            lock.readLock().unlock();
        }
    }
}

运行可以看到写入是一个一个写完 但是读取可以插队

标签:java,String,ReadWriteLock,读写,util,key,lock,Java,import
来源: https://www.cnblogs.com/OfflineBoy/p/15266601.html