当前位置:网站首页>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队列:带头结点的双向非循环链表
边栏推荐
- wx. Getlocation (object object) application method, latest version
- MySQL functions
- NSSA area where OSPF is configured for Huawei equipment
- NLP basic task word segmentation third party Library: ICTCLAS [the third party library with the highest accuracy of Chinese word segmentation] [Chinese Academy of Sciences] [charge]
- 从底层结构开始学习FPGA----FIFO IP核及其关键参数介绍
- FPGA内部硬件结构与代码的关系
- anconda下载+添加清华+tensorflow 安装+No module named ‘tensorflow‘+KernelRestarter: restart failed,内核重启失败
- Set data real-time update during MDK debug
- What is information security? What is included? What is the difference with network security?
- 云导DNS和知识科普以及课堂笔记
猜你喜欢
Folding and sinking sand -- weekly record of ETF
Arduino六足机器人
如何制作自己的机器人
uniapp开发,打包成H5部署到服务器
The relationship between FPGA internal hardware structure and code
如何解决ecology9.0执行导入流程流程产生的问题
Analysis of the combination of small program technology advantages and industrial Internet
Mysql - CRUD
MySQL存储引擎
Priority queue (heap)
随机推荐
[noi simulation] Anaid's tree (Mobius inversion, exponential generating function, Ehrlich sieve, virtual tree)
The relationship between FPGA internal hardware structure and code
LeetCode 8. String conversion integer (ATOI)
Opencv classic 100 questions
Uniapp development, packaged as H5 and deployed to the server
常用API类及异常体系
Spark-SQL UDF函数
MySql——CRUD
数据分析思维分析方法和业务知识——分析方法(三)
认识提取与显示梅尔谱图的小实验(观察不同y_axis和x_axis的区别)
[EI conference sharing] the Third International Conference on intelligent manufacturing and automation frontier in 2022 (cfima 2022)
Browser local storage
Free chat robot API
Spark DF增加一列
Location based mobile terminal network video exploration app system documents + foreign language translation and original text + guidance records (8 weeks) + PPT + review + project source code
FFMPEG关键结构体——AVFormatContext
LeetCode 1189. Maximum number of "balloons"
[Chongqing Guangdong education] Chongqing Engineering Vocational and Technical College
剖面测量之提取剖面数据
Comment faire votre propre robot