当前位置:网站首页>代码实例详解【可重入锁】和【不可重入锁】区别?
代码实例详解【可重入锁】和【不可重入锁】区别?
2022-07-26 11:46:00 【用户9919783】
首先我们要明白锁的概念,在多线程的场景下,不同的线程一起运行会导致脏数据,为了保证线程安全,这时候便出现了锁的概念,锁可以对代码块,资源,对象上锁,上锁之后,只允许一个线程对其进行操作,其他线程都会进入阻塞状态,这也就是阻塞加锁方法,直到锁释放之后,其他线程才可以获取锁对其操作。
之前文章重点单独介绍过Synchronized和Reentrantlock,不明白的同学可以先看看了解:
currentHashMap的公平锁,可中断响应,限制等待实例
这篇文章主要是介绍可重入锁和不可重入锁,在jdk中synchronized和Reentrantlock,都是可重入锁,为了更高效的性能和防止发生死锁。
可重入锁可以理解为:同一个线程下,外层方法上锁之后,内层调用的方法也能正常获取锁。
下面先用代码介绍对【不可重入锁】的理解。
当testA()方法获取锁之后,在业务里调用testB(),此时因为A的锁未释放,所以B不能获取到锁,这时候B的业务不能正常进行下去,导致A也不能正常释放锁,A和B方法就发生了死锁。这就是不可重入锁。
可重入锁是什么呢?
Jdk中带的基本都是可重入锁,下面就用synchronized实例介绍,在锁住同一个object之后,控制台打印可以看出,threadA调用threadB方法,B和A方法不会发生死锁,业务都能进行下去。
我们自己可以用synchronized + wait + notify来实现不可重入锁,代码如下:
边栏推荐
- Marriage seeking story
- 系统调用捕获和分—Ring3层LD_PRELOAD机制进行库函数劫持
- Leetcode / Scala - sum of two numbers, three numbers, four numbers, and N numbers
- 百问百答第48期:极客有约——可观测体系的建设路径
- Acwing727.菱形图案
- Machine learning by Li Hongyi 2. Regression
- 专访即构科技李凯:音视频的有趣、行业前沿一直吸引着我
- 元宇宙GameFi链游系统开发NFT技术
- 什么是Per-Title编码?
- 数据数据湖(十九):SQL API 读取Kafka数据实时写入Iceberg表
猜你喜欢

7月27日19:30直播预告:HarmonyOS3及华为全场景新品发布会

如何使用数据管道实现测试现代化

How to use data pipeline to realize test modernization

Live broadcast preview at 19:30 on July 27: harmonyos3 and Huawei's full scene new product launch

What is per title encoding?

Talking about web vitals

了解 useRef 一篇就够了
![[countdown 10 days] Tencent cloud audio and video special is about to meet, and the thousand yuan prize is waiting for you!](/img/a0/4910970a089cab198875944c7ae88c.png)
[countdown 10 days] Tencent cloud audio and video special is about to meet, and the thousand yuan prize is waiting for you!

。。。。。。

4.1 configure MySQL and register login module
随机推荐
Substance painter 2021 software installation package download and installation tutorial
哈希表
Several inventory terms often used in communication
科目三 掉头与转弯
Swagger2.9.2 tutorial and swagger3.0.0 tutorial
3.2 创建菜单与游戏页面(下)
Win10 uses NVM to install node, NPM, and cnpm
Sword finger offer 25. merge two sorted linked lists
How did the $50000 annual salary run out
Fineos announced the open registration of grouptech connect activities in 2022
Talking about web vitals
Test cases should never be used casually, recording the thinking caused by the exception of a test case
Outsourcing for four years, abandoned
pytest接口自动化测试框架 | 使用多个fixture
[communication principle] Chapter 3 -- random process [i]
Pytorch——基于mmseg/mmdet训练报错:RuntimeError: Expected to have finished reduction in the prior iteration
On the construction and management of low code technology in logistics transportation platform
pytest接口自动化测试框架 | pytest的setup和teardown函数
PyCharm是真的强
pytest接口自动化测试框架 | conftest.py