Java锁之可重入锁介绍
锁作为并发共享数据,保证一致性的工具,在JAVA平台有多种实现(如synchronized和ReentrantLock等等)。这些已经写好提供的锁为我们开发提供了便利,但是锁的具体性质以及类型却很少被提及。本系列文章将分析JAVA下常见的锁名称以及特性,为大家答疑解惑。
四、可重入锁:
本文里面讲的是广义上的可重入锁,而不是单指JAVA下的ReentrantLock。
可重入锁,也叫做递归锁,指的是同一线程外层函数获得锁之后,内层递归函数仍然有获取该锁的代码,但不受影响。
在JAVA环境下ReentrantLock和synchronized都是可重入锁。
下面是使用实例:
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();
}
}
两个例子最后的结果都是正确的,即同一个线程id被连续输出两次。
结果如下:
Threadid:8
Threadid:8
Threadid:10
Threadid:10
Threadid:9
Threadid:9
可重入锁最大的作用是避免死锁。
我们以自旋锁作为例子。
对于自旋锁来说: 1、若有同一线程两调用lock(),会导致第二次调用lock位置进行自旋,产生了死锁 修改之后,如下: while(!owner.compareAndSet(null,current)){ } } } 该自旋锁即为可重入锁。
publicclassSpinLock{
privateAtomicReference<Thread>owner=newAtomicReference<>();
publicvoidlock(){
Threadcurrent=Thread.currentThread();
while(!owner.compareAndSet(null,current)){
}
}
publicvoidunlock(){
Threadcurrent=Thread.currentThread();
owner.compareAndSet(current,null);
}
}
说明这个锁并不是可重入的。(在lock函数内,应验证线程是否为已经获得锁的线程)
2、若1问题已经解决,当unlock()第一次调用时,就已经将锁释放了。实际上不应释放锁。
(采用计数次进行统计)
publicclassSpinLock1{
privateAtomicReference<Thread>owner=newAtomicReference<>();
privateintcount=0;
publicvoidlock(){
Threadcurrent=Thread.currentThread();
if(current==owner.get()){
count++;
return;
}
}
publicvoidunlock(){
Threadcurrent=Thread.currentThread();
if(current==owner.get()){
if(count!=0){
count--;
}else{
owner.compareAndSet(current,null);
}
}
相关文章