简单了解Java中的可重入锁
这篇文章主要介绍了简单了解Java中的可重入锁,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
本文里面讲的是广义上的可重入锁,而不是单指JAVA下的ReentrantLock。
可重入锁,也叫做递归锁,指的是同一线程外层函数获得锁之后,内层递归函数仍然有获取该锁的代码,但不受影响。
在JAVA环境下ReentrantLock和synchronized都是可重入锁。
下面是使用实例:
packagereentrantLock;
publicclassTestimplementsRunnable{
publicsynchronizedvoidget(){
System.out.println(Thread.currentThread().getId());
set();
}
publicsynchronizedvoidset(){
System.out.println(Thread.currentThread().getId());
}
@Override
publicvoidrun(){
get();
}
publicstaticvoidmain(String[]args){
Testss=newTest();
newThread(ss).start();
newThread(ss).start();
newThread(ss).start();
}
}
运行截图:
packagereentrantLock;
importjava.util.concurrent.locks.ReentrantLock;
publicclassTestimplementsRunnable{
ReentrantLocklock=newReentrantLock();
publicvoidget(){
lock.lock();
System.out.println(Thread.currentThread().getId());
set();
lock.unlock();
}
publicvoidset(){
lock.lock();
System.out.println(Thread.currentThread().getId());
lock.unlock();
}
@Override
publicvoidrun(){
get();
}
publicstaticvoidmain(String[]args){
Testss=newTest();
newThread(ss).start();
newThread(ss).start();
newThread(ss).start();
}
}
可重入锁最大的作用是避免死锁
我们以自旋锁作为例子,
publicclassSpinLock{
privateAtomicReferenceowner=newAtomicReference<>();
publicvoidlock(){
Threadcurrent=Thread.currentThread();
while(!owner.compareAndSet(null,current)){
}
}
publicvoidunlock(){
Threadcurrent=Thread.currentThread();
owner.compareAndSet(current,null);
}
}
对于自旋锁来说,
1、若有同一线程两调用lock(),会导致第二次调用lock位置进行自旋,产生了死锁说明这个锁并不是可重入的。(在lock函数内,应验证线程是否为已经获得锁的线程)
2、若1问题已经解决,当unlock()第一次调用时,就已经将锁释放了。实际上不应释放锁。(采用计数次进行统计)修改之后,如下:
publicclassSpinLock1{
privateAtomicReferenceowner=newAtomicReference<>();
privateintcount=0;
publicvoidlock(){
Threadcurrent=Thread.currentThread();
if(current==owner.get()){
count++;
return;
}
while(!owner.compareAndSet(null,current)){
}
}
publicvoidunlock(){
Threadcurrent=Thread.currentThread();
if(current==owner.get()){
if(count!=0){
count--;
}else{
owner.compareAndSet(current,null);
}
}
}
}
该自旋锁即为可重入锁。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。