读写锁 代码演示

读写锁 保证写的原子性,写是独占,读是可以共享的

package com.myspringboot.test;

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

/*
 * @Description:    读写锁 写:独占+原子 读:共享  
 * @Author: WDC 
 * @Date: 2020/3/19 15:25
 **/
class MyCache{
     
    private volatile Map<String,Object> map = new HashMap<>();
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    public void put(String key,Object value){
     
        rwLock.writeLock().lock();
        try{
     
            System.out.println(Thread.currentThread().getName()+"\t正在写入" + key);
            //暂停一下,模拟一下网络拥堵
//            try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t写入完成");
        }catch(Exception e){
     
            e.printStackTrace();
        }finally{
     
            rwLock.writeLock().unlock();
        }
    }
    public void get(String key){
     
        rwLock.readLock().lock();
        try{
     
            System.out.println(Thread.currentThread().getName()+"\t正在读取");
            //暂停一下,模拟一下网络拥堵
            try {
      TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) {
      e.printStackTrace(); }
            Object result = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t读取完成" + result);
        }catch(Exception e){
     
            e.printStackTrace();
        }finally{
     
            rwLock.readLock().unlock();
        }
    }
    public void clear(){
     
        map.clear();
    }
}

public class ReadWriteLockDemo {
     
    public static void main(String[] args) {
     
        MyCache myCache = new MyCache();
        for (int i = 1; i <= 5; i++){
     
            final int tempInt = i;
            new Thread(()->{
     
                myCache.put(tempInt+"",tempInt+"");
            },String.valueOf(i)).start();
        }
       // try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
        for (int i = 1; i <= 5; i++){
     
            final int tempInt = i;
            new Thread(()->{
     
                myCache.get(tempInt+"");
            },String.valueOf(i)).start();
        }
    }
}

你可能感兴趣的:(代码演示)