当前位置:网站首页>ReentrantLock原理(未完待续)
ReentrantLock原理(未完待续)
2022-07-31 19:21:00 【斯沃福德】
1. 概述
ReentrantLock底层基于AQS,其构造方法返回的就是NonfaireSync和faireSync;
两种同步器都继承自Sync,Sync又继承自AQS!
new ReentrantLock时,返回的就是同步器,默认是非公平的;
2. 非公平锁的加锁
2. 1 加锁成功
调用lock() 方法,使用CAS机制尝试将AQS底层 volatile修饰的 state 属性改为1,若成功即加锁;
若失败即出现竞争,则进入acquire() 方法;
2. 2 加锁失败
- 当锁已经被占用,共享内存中的 state属性是1,compareAndSet(0,1) 会失败,CAS更改state属性失败,会进入 acquire() 方法;
- 进入else中 AQS的 acquire() 方法;
- 调用 tryAcquire() 再次尝试,结果为false,取反就是true,再执行acquireQueued() ,会创造一个Node节点对象关联线程,放到FIFO等待队列(双向链表)中;
- 节点进入队列后,会循环尝试加锁,失败后会被park阻塞,节点的waitStatus 会被置为 -1,后续会由前序节点来唤醒这个节点;
AQS中的acquire()方法:
假设多个线程多竞争失败,进入了FIFO等待队列:
2. 非公平锁的释放
2.1 竞争成功
- 调用 unlock() 方法,底层调用了release() 方法,使用tryRelease() 将state置为0即释放锁;
- tryRelease() 返回true后,判断head哨兵节点是否为null ,如果否且哨兵节点的waitStatus 也不会0(为-1),则哨兵节点的后继节点被unParkSuccessor 唤醒 !然后这个后继节点会从FIFO队列中移除;
2.1 竞争失败
边栏推荐
- PCB叠层设计
- 有一说一,外包公司到底值不值得去?
- 【AcWing】第 62 场周赛 【2022.07.30】
- MySQL---Create and manage databases and data tables
- 深度学习中的batch(batch size,full batch,mini batch, online learning)、iterations与epoch
- MySQL---Basic select statement
- Huawei mobile phone one-click to open "maintenance mode" to hide all data and make mobile phone privacy more secure
- 广汽本田安全体验营:“危险”是最好的老师
- 全网一触即发,自媒体人的内容分发全能助手——融媒宝
- What's wrong with the sql syntax in my sql
猜你喜欢
GateWay实现负载均衡
Go basic part study notes
请问我的这段sql中sql语法哪里出了错
Chinese encoding Settings and action methods return values
21.支持向量机—核函数的介绍
如何才能真正的提高自己,成为一名出色的架构师?
【码蹄集新手村600题】通向公式与程序相结合
全网一触即发,自媒体人的内容分发全能助手——融媒宝
Jiuqi ny3p series voice chip replaces the domestic solution KT148A, which is more cost-effective and has a length of 420 seconds
35道MySQL面试必问题图解,这样也太好理解了吧
随机推荐
高通cDSP简单编程例子(实现查询高通cDSP使用率、签名),RK3588 npu使用率查询
AI 自动写代码插件 Copilot(副驾驶员)
ojdbc8 "Recommended Collection"MATLAB程序设计与应用 2.4 MATLAB常用内部函数
spark报错OutOfMemory「建议收藏」
【码蹄集新手村600题】通向公式与程序相结合
Architect 04 - Application Service Encryption Design and Practice
leetcode 665. Non-decreasing Array
MySQL - multi-table query
Getting Started with Tkinter
STM32 full series development firmware installation guide under Arduino framework
UserAgent 解析
Verilog实现占空比为5/18的9分频
matplotlib ax bar color Set the color, transparency, label legend of the ax bar
MySQL---创建和管理数据库和数据表
MySQL - single function
npm 更改为淘宝镜像的方法[通俗易懂]
Combinatorics Notes (6) Associative Algebra of Locally Finite Partially Ordered Sets, Möbius Inversion Formula
Basic configuration of OSPFv3
flowable工作流所有业务概念