ReadWriteLock

ReadWriteLock 读写锁,只有读读不互斥,其他都互斥。写了个小demo,来加深下印象。
public class MyChahe {

    private Map map=new HashMap<>();

    private ReadWriteLock lock=new ReentrantReadWriteLock();

    public void put(String key,Object value){
        try{
            lock.writeLock().lock();
            System.out.println("现在开始进行put操作----------");
            map.put(key,value);
            Thread.sleep(5000);
            System.out.println("put操作结束----------");
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            lock.writeLock().unlock();
        }
    }

    public void get(String key){
        try{
            lock.readLock().lock();
            System.out.println("现在开始进行get操作----------");
            Object value = map.get(key);
            System.out.println("get操作结束----------,value-->"+value);
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            lock.readLock().unlock();
        }
    }
}
public class LockTest {

    public static void main(String[] args) throws InterruptedException {
        MyChahe cache=new MyChahe();
        new Thread(()->{
            cache.put("1","aaaaaaaaaa");
        }).start();

        Thread.sleep(300);

        new Thread(()->{
            cache.get("1");
        }).start();
    }
}

当有线程获取写锁的时候,其他线程去调用读相关操作,没办法获取读锁,只能等待写锁释放,才可以获取。

你可能感兴趣的:(javalock)