当前位置:网站首页>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队列:带头结点的双向非循环链表
边栏推荐
- Solve the problem of reading Chinese garbled code in sqlserver connection database
- XML配置文件
- Idea远程提交spark任务到yarn集群
- Multithreading and high concurrency (8) -- summarize AQS shared lock from countdownlatch (punch in for the third anniversary)
- LeetCode 6005. The minimum operand to make an array an alternating array
- Spark SQL UDF function
- Go learning --- read INI file
- XML Configuration File
- MDK debug时设置数据实时更新
- Recognize the small experiment of extracting and displaying Mel spectrum (observe the difference between different y_axis and x_axis)
猜你喜欢

Huawei equipment is configured with OSPF and BFD linkage

FFMPEG关键结构体——AVFrame

Huawei equipment configuration ospf-bgp linkage

Introduction of motor

Start from the bottom structure and learn the introduction of fpga---fifo IP core and its key parameters

NSSA area where OSPF is configured for Huawei equipment

数据分析思维分析方法和业务知识——分析方法(二)

About the slmgr command

Determinant learning notes (I)

Spark SQL null value, Nan judgment and processing
随机推荐
Codeforces Round #804 (Div. 2)【比赛记录】
Solve the problem of reading Chinese garbled code in sqlserver connection database
Hardware and interface learning summary
An understanding of & array names
Reading notes of the beauty of programming
Pointer - character pointer
AtCoder Beginner Contest 254【VP记录】
Go learning - dependency injection
[Chongqing Guangdong education] Chongqing Engineering Vocational and Technical College
FFmpeg抓取RTSP图像进行图像分析
N1 # if you work on a metauniverse product [metauniverse · interdisciplinary] Season 2 S2
关于slmgr命令的那些事
Huawei equipment is configured with OSPF and BFD linkage
Calculate sha256 value of data or file based on crypto++
LeetCode 1189. Maximum number of "balloons"
时间戳的拓展及应用实例
STM32 configuration after chip replacement and possible errors
Codeforces round 804 (Div. 2) [competition record]
Spark SQL UDF function
云导DNS和知识科普以及课堂笔记