zoukankan      html  css  js  c++  java
  • Java多线程-读写锁ReentrantReadWriteLock类

    共享锁 与 排他锁

    ReentrantReadWriteLock类有两个锁,一个是读操作相关的锁,即共享锁。另一个是写操作相关的锁,即排他锁。

    也就是多个读锁之间不互斥,读锁与写锁互斥,写锁与写锁互斥。

    读锁与读锁共享

    示例:

    public class Test {
        public static void main(String[] args) {
            Service service = new Service();
            new Thread(() -> service.read(), "A").start();
            new Thread(() -> service.read(), "B").start();
        }
    
        static class Service {
            private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
            public void read() {
                lock.readLock().lock();
                try {
                    System.out.println("线程" + Thread.currentThread().getName() + "获得读锁 " + System.currentTimeMillis());
                    Thread.sleep(2000);
                    System.out.println("线程" + Thread.currentThread().getName() + "读取完毕");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.readLock().unlock();
                }
    
            }
        }
    }

    运行结果如下:

    读锁与写锁互斥

    示例:

    public class Test {
        public static void main(String[] args) {
            Service service = new Service();
            new Thread(() -> service.read(), "A").start();
            new Thread(() -> service.read(), "B").start();
        }
    
        static class Service {
            private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
            public void read() {
                lock.writeLock().lock();
                try {
                    System.out.println("线程" + Thread.currentThread().getName() + "获得写锁 " + System.currentTimeMillis());
                    Thread.sleep(2000);
                    System.out.println("线程" + Thread.currentThread().getName() + "写完毕");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.writeLock().unlock();
                }
    
            }
        }
    }

    运行结果如下:

  • 相关阅读:
    Kubernetes 部署 Kubernetes-Dashboard v2.0.0
    Kubernetes 部署 Metrics Server 获取集群指标数据
    内网终端安全建设(转)
    内网安全运营的逻辑体系架构(转)
    thinkphp5配置文件
    MySQL索引失效的几种情况
    workman使用
    长连接技术(Long Polling)
    php好文章的记录
    php类与对象得使用场景
  • 原文地址:https://www.cnblogs.com/lkc9/p/12565042.html
Copyright © 2011-2022 走看看