当前位置:   article > 正文

readWriteLock的使用

readWriteLock的使用
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by byteyoung on 2020/8/24.
 */
public class readWriteLock{
    public static void main(String[] args) {
        MycacheLock mycache = new MycacheLock();
        for (int i = 0; i <10 ; i++) {
            final int tem = i ;
            new Thread(()->{

                mycache.put(String.valueOf(tem),""+tem);
            },String.valueOf(tem)).start();

        }
        //read

        for (int i = 0; i <10 ; i++) {
            final int tem = i ;
            new Thread(()->{

                mycache.get(tem+"");
            },String.valueOf(tem)).start();

        }
    }


}
class MycacheLock{
    private volatile Map<String ,Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock ();
    //更加细粒度的控制

    public void put(String key ,Object value){
        //Lock.lock();
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key);

            map.put(key,value);

            System.out.println(Thread.currentThread().getName()+"写入ok"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }

    }
    public void get(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取ok"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }

    }
}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/956211
推荐阅读
相关标签
  

闽ICP备14008679号