ReentrantReadWriteLock--ReadWriteLock显示锁系列( 手动管理锁)

内部锁(自动锁 JVM管理):通过synchronized关键字实现
显示锁(手动锁 手动管理锁 功能更多):通过java.concurrent.locks.Lock接口的实现类
 

                                ReentrantReadWriteLock 读写锁

好处

  1. 提高并发性能:读写锁可以提高并发程序的读性能,多个读可同时执行

写前线程共享,写时排他锁,允许多个线程同时读取共享数据,但一次只允许一个线程对共享数据进行更新,当一个线程持有读锁/写锁时,其他线程都无法获得写锁。

和lock的区别是,lock只支持排他模式,独占共享资源,而读写锁同时具有共享模式和排他模式
另外在此基础之上,支持公平锁,具有可重入性
 

readLock().lock(); 拿到读锁
writeLock().lock();拿到写锁
用了哪个记得unlock()

 

特点:线程之间:读读共享 写写互斥 读写互斥    (指的是交叉或排队执行)

  static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();  
public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            new Thread(new T3()).start();
        }
    }
    @Override
    public void run() {
        try {
            readWriteLock.writeLock().lock();
            //readWriteLock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+"---获得锁开始写入"+new Date());
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            在不释放的情况下,读锁多个线程可以同时拿到锁读到共享数据,不排队
            多个线程只能排队拿写锁 互斥。
        }

  static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static int i=3;
   public static void test() {
       try {
           readWriteLock.readLock().lock();
           System.out.println(Thread.currentThread().getName()+"---读锁"+i);
           Thread.sleep(2000);
           System.out.println(Thread.currentThread().getName()+"---读锁完成"+i);
       } catch (InterruptedException e) {
           throw new RuntimeException(e);
       }finally {
           读写锁共存时,就是读写互斥的,读锁若没释放,写锁拿不到锁了
            就是讲读和写单独存在时,写锁的获取是需要读锁释放的
       }
   }
    public static void test2() {
        try {
            readWriteLock.writeLock().lock();

            System.out.println(Thread.currentThread().getName()+"---写锁"+i);
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName()+"---写锁over"+i);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
           
        }
    }
    public static void main(String[] args) throws InterruptedException {

        new Thread(T3::test).start();
        new Thread(T3::test2).start();

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值