当前位置:网站首页>synchronized 和 ReentrantLock
synchronized 和 ReentrantLock
2022-07-06 00:33:00 【InfoQ】
synchronized 和 ReentrantLock 有什么区别?
- synchronized 和 ReentrantLock 都提供了锁的功能
- ReentrantLock 可设置为公平锁,而 synchronized 不能
- ReentrantLock 只能修饰代码块,而 synchronized 可以用于修饰方法、修饰代码块等;
- ReentrantLock 需要手动加锁和释放锁,锁没有释放,则会造成资源被占用一直得不到释放,而 synchronized 无需手动释放锁,由jvm内部自动加锁和释放锁
- ReentrantLock 可以主动的获取是否成功获得了锁的信息,而 synchronized 不行,可以理解为黑盒方法
使用
Lock lock = new ReentrantLock();
try {
lock.lock();
} finally {
lock.unlock();
}
- 直接修饰在方法声明上
- 声明在方法块中
原理的区别
- 每个对象有一个锁monitor,当monitor被占用时就会处于锁定状态
- 如果monitor的进入数为0,则该线程进入monitor,然后将进入数设置为1,该线程即为monitor的所有者
- 如果monitor的进入数不为0,则表示已有线程进入monitor,则该线程进入阻塞状态
- 线程执行完成后,退出monitor,将进入数设置为0
- CAS:Compare and Swap,比较并交换,此操作为一个原子操作
- CLH队列:带头结点的双向非循环链表
边栏推荐
- The relationship between FPGA internal hardware structure and code
- [noi simulation] Anaid's tree (Mobius inversion, exponential generating function, Ehrlich sieve, virtual tree)
- Basic introduction and source code analysis of webrtc threads
- notepad++正則錶達式替換字符串
- Extension and application of timestamp
- JS can really prohibit constant modification this time!
- How to solve the problems caused by the import process of ecology9.0
- Knowledge about the memory size occupied by the structure
- anconda下载+添加清华+tensorflow 安装+No module named ‘tensorflow‘+KernelRestarter: restart failed,内核重启失败
- Opencv classic 100 questions
猜你喜欢

【DesignMode】组合模式(composite mode)

NSSA area where OSPF is configured for Huawei equipment

Hudi of data Lake (2): Hudi compilation

Intranet Security Learning (V) -- domain horizontal: SPN & RDP & Cobalt strike

Arduino六足机器人

剖面测量之提取剖面数据

wx. Getlocation (object object) application method, latest version

Room cannot create an SQLite connection to verify the queries

Idea remotely submits spark tasks to the yarn cluster

The relationship between FPGA internal hardware structure and code
随机推荐
数据分析思维分析方法和业务知识——分析方法(三)
STM32按键消抖——入门状态机思维
Codeforces Round #804 (Div. 2)【比赛记录】
MySql——CRUD
如何制作自己的机器人
Mysql - CRUD
AtCoder Beginner Contest 258【比赛记录】
2022.7.5-----leetcode. seven hundred and twenty-nine
MySQL functions
Idea远程提交spark任务到yarn集群
LeetCode 1598. Folder operation log collector
Spark-SQL UDF函数
Reading notes of the beauty of programming
SQLServer连接数据库读取中文乱码问题解决
notepad++正則錶達式替換字符串
[Chongqing Guangdong education] reference materials for Zhengzhou Vocational College of finance, taxation and finance to play around the E-era
STM32 key chattering elimination - entry state machine thinking
LeetCode 6004. Get operands of 0
MySQL存储引擎
如何制作自己的機器人