Java锁之可重入锁介绍
作者:junjie 时间:2021-06-01 03:05:19
锁作为并发共享数据,保证一致性的工具,在JAVA平台有多种实现(如 synchronized 和 ReentrantLock等等 ) 。这些已经写好提供的锁为我们开发提供了便利,但是锁的具体性质以及类型却很少被提及。本系列文章将分析JAVA下常见的锁名称以及特性,为大家答疑解惑。
四、可重入锁:
本文里面讲的是广义上的可重入锁,而不是单指JAVA下的ReentrantLock。
可重入锁,也叫做递归锁,指的是同一线程 外层函数获得锁之后 ,内层递归函数仍然有获取该锁的代码,但不受影响。
在JAVA环境下 ReentrantLock 和synchronized 都是 可重入锁。
下面是使用实例:
public class Test implements Runnable{
public synchronized void get(){
System.out.println(Thread.currentThread().getId());
set();
}
public synchronized void set(){
System.out.println(Thread.currentThread().getId());
}
@Override
public void run() {
get();
}
public static void main(String[] args) {
Test ss=new Test();
new Thread(ss).start();
new Thread(ss).start();
new Thread(ss).start();
}
}
两个例子最后的结果都是正确的,即 同一个线程id被连续输出两次。
结果如下:
Threadid: 8
Threadid: 8
Threadid: 10
Threadid: 10
Threadid: 9
Threadid: 9
可重入锁最大的作用是避免死锁。
我们以自旋锁作为例子。
public class SpinLock {
private AtomicReference<Thread> owner =new AtomicReference<>();
public void lock(){
Thread current = Thread.currentThread();
while(!owner.compareAndSet(null, current)){
}
}
public void unlock (){
Thread current = Thread.currentThread();
owner.compareAndSet(current, null);
}
}
对于自旋锁来说:
1、若有同一线程两调用lock() ,会导致第二次调用lock位置进行自旋,产生了死锁
说明这个锁并不是可重入的。(在lock函数内,应验证线程是否为已经获得锁的线程)
2、若1问题已经解决,当unlock()第一次调用时,就已经将锁释放了。实际上不应释放锁。
(采用计数次进行统计)
修改之后,如下:
public class SpinLock1 {
private AtomicReference<Thread> owner =new AtomicReference<>();
private int count =0;
public void lock(){
Thread current = Thread.currentThread();
if(current==owner.get()) {
count++;
return ;
}
while(!owner.compareAndSet(null, current)){
}
}
public void unlock (){
Thread current = Thread.currentThread();
if(current==owner.get()){
if(count!=0){
count--;
}else{
owner.compareAndSet(current, null);
}
}
}
}
该自旋锁即为可重入锁。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#中POST接口formdata传参模板的记录
Android模拟实现支付宝蚂蚁森林效果
![](https://img.aspxhome.com/file/2023/1/105981_0s.png)
C#实现自定义Dictionary类实例
![](https://img.aspxhome.com/file/2023/7/116457_0s.png)
Android开发使用RecyclerView添加点击事件实例详解
Springboot如何根据实体类生成数据库表
![](https://img.aspxhome.com/file/2023/7/59677_0s.jpg)
java HashMap和HashTable的区别详解
C语言算法积累加tag的循环队列
详解JDK自带javap命令反编译class文件和Jad反编译class文件(推荐使用jad)
![](https://img.aspxhome.com/file/2023/3/97803_0s.png)
Java NIO实战之多人聊天室
AsyncTask官方文档教程整理
Java Druid连接池与Apache的DBUtils使用教程
![](https://img.aspxhome.com/file/2023/8/96818_0s.png)
spring mvc中@RequestBody注解的作用说明
![](https://img.aspxhome.com/file/2023/4/62764_0s.png)
Android开发中使用Intent打开第三方应用及验证可用性的方法详解
基于JAVA中Jersey处理Http协议中的Multipart的详解
JPA save()方法将字段更新为null的解决方案
Java中通过jsch来连接远程服务器执行linux命令
springboot中bean的加载顺序问题
![](https://img.aspxhome.com/file/2023/0/62510_0s.png)
C#中的静态成员、静态方法、静态类介绍
![](https://img.aspxhome.com/file/2023/1/92961_0s.jpg)
超简洁java实现双色球若干注随机号码生成(实例代码)
![](https://img.aspxhome.com/file/2023/9/91119_0s.png)
C#设计模式之Singleton模式
![](https://img.aspxhome.com/file/2023/5/86995_0s.png)