美文网首页
ReentrantReadWriteLock 的使用

ReentrantReadWriteLock 的使用

作者: 坚持编程_lyz | 来源:发表于2017-06-24 21:21 被阅读206次
    ReentrantReadWriteLock 是一个锁对象,他支持读数据锁和写数据锁;
    

    适合的使用场景

    1. 多线程环境
    2. 并且共同访问同一个资源数据
    3. 要求可以共享读数据,同时读
    4. 不能同时写数据
    

    注意事项

    • 读操作可以多线程同时一起读数据
    • 但在写的时候,多个线程只能有一个线程在写,并且写的同时不允许去读数据

    使用方式

       public static void main(String[] args) {
            //创建并发访问的账户
            MyCount myCount = new MyCount("95599200901215522", 10000);
            //创建一个锁对象
            ReadWriteLock lock = new ReentrantReadWriteLock(false);
            //创建一个线程池
            ExecutorService pool = Executors.newFixedThreadPool(2);
    //        ExecutorService pool = Executors.newCachedThreadPool();
            //创建一些并发访问用户,一个信用卡,存的存,取的取,好热闹啊
            User u1 = new User("张三", myCount, -4000, lock, false);
            User u2 = new User("张三他爹", myCount, 6000, lock, false);
            User u3 = new User("张三他弟", myCount, -8000, lock, false);
            User u4 = new User("张三", myCount, 800, lock, false);
            User u5 = new User("张三他爹", myCount, 0, lock, true);
            //在线程池中执行各个用户的操作,2个线程池大家在用
            // u1 和 u2 两个抢一个执行lock
            pool.execute(u1);
            pool.execute(u2);
            pool.execute(u3);
            pool.execute(u4);
            pool.execute(u5);
            //关闭线程池
            pool.shutdown();
        }
    }
    
    
    class User implements Runnable {
        private String name;                 //用户名
        private MyCount myCount;         //所要操作的账户
        private int iocash;                 //操作的金额,当然有正负之分了
        private ReadWriteLock myLock;                 //执行操作所需的锁对象
        private boolean ischeck;         //是否查询
    
        User(String name, MyCount myCount, int iocash, ReadWriteLock myLock, boolean ischeck) {
            this.name = name;
            this.myCount = myCount;
            this.iocash = iocash;
            this.myLock = myLock;
            this.ischeck = ischeck;
        }
    
        public void run() {
            if (ischeck) {
                //获取读锁
                myLock.readLock().lock();
                System.out.println("读:" + name + "正在查询" + myCount + "账户,当前金额为" + myCount.getCash());
    //            释放读锁
                myLock.readLock().unlock();
            } else {
                //获取写锁: 同一时间只能有一个线程执行操作
                myLock.writeLock().lock();
                //执行现金业务
                System.out.println("写:" + name + "正在操作" + myCount + "账户,金额为" + iocash + ",当前金额为" + myCount.getCash());
                myCount.setCash(myCount.getCash() + iocash);
                System.out.println("写:" + name + "操作" + myCount + "账户成功,金额为" + iocash + ",当前金额为" + myCount.getCash());
                //释放写锁
                myLock.writeLock().unlock();
            }
        }
    }
    
    
    class MyCount {
        private String oid;         //账号
        private int cash;             //账户余额
    
        MyCount(String oid, int cash) {
            this.oid = oid;
            this.cash = cash;
        }
    
        public String getOid() {
            return oid;
        }
    
        public void setOid(String oid) {
            this.oid = oid;
        }
    
        public int getCash() {
            return cash;
        }
    
        public void setCash(int cash) {
            this.cash = cash;
        }
    
        @Override
        public String toString() {
            return "MyCount{" +
                    "oid='" + oid + '\'' +
                    ", cash=" + cash +
                    '}';
        }
    }
    

    打印结果

    写:张三他爹正在操作MyCount{oid='95599200901215522', cash=10000}账户,金额为6000,当前金额为10000
    写:张三他爹操作MyCount{oid='95599200901215522', cash=16000}账户成功,金额为6000,当前金额为16000
    写:张三正在操作MyCount{oid='95599200901215522', cash=16000}账户,金额为-4000,当前金额为16000
    写:张三操作MyCount{oid='95599200901215522', cash=12000}账户成功,金额为-4000,当前金额为12000
    写:张三他弟正在操作MyCount{oid='95599200901215522', cash=12000}账户,金额为-8000,当前金额为12000
    写:张三他弟操作MyCount{oid='95599200901215522', cash=4000}账户成功,金额为-8000,当前金额为4000
    写:张三正在操作MyCount{oid='95599200901215522', cash=4000}账户,金额为800,当前金额为4000
    写:张三操作MyCount{oid='95599200901215522', cash=4800}账户成功,金额为800,当前金额为4800
    读:张三他爹正在查询MyCount{oid='95599200901215522', cash=4800}账户,当前金额为4800
    

    实际项目使用

      public void cluster() {
            mClusterTaskLock.writeLock().lock();//加锁避免并发修改数据
            try {
                // Attempt to cancel the in-flight request.
                mClusterTask.cancel(true);
                mClusterTask = new ClusterTask();
    
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
                    mClusterTask.execute(mMap.getMapStatus().zoom);
                } else {
                    mClusterTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mMap.getMapStatus().zoom);
                }
            } finally {
                mClusterTaskLock.writeLock().unlock();//用完释放
            }
        }
    
    

    读和写一起使用

        private Set<? extends Cluster<T>> getClustersInternal(int discreteZoom) {
            Set<? extends Cluster<T>> results;
            mCacheLock.readLock().lock();
            results = mCache.get(discreteZoom);
            mCacheLock.readLock().unlock();
    
            if (results == null) {
                mCacheLock.writeLock().lock();
                results = mCache.get(discreteZoom);
                if (results == null) {
                    results = mAlgorithm.getClusters(discreteZoom);
                    mCache.put(discreteZoom, results);
                }
                mCacheLock.writeLock().unlock();
            }
            return results;
        }
    

    相关文章

      网友评论

          本文标题:ReentrantReadWriteLock 的使用

          本文链接:https://www.haomeiwen.com/subject/bjakcxtx.html