可重入锁,也称为递归锁,,在同一线程3358 www.Sina.com /函数被锁定后,返回http://www.Sina.com
这篇文章介绍了外层,而不仅仅是指向JAVA下的ReentrantLock。
可重入锁也称为递归锁,即使同一线程的外部函数获得锁,内部递归函数也有获得该锁的代码,但不受影响。
在JAVA环境中,保留锁定和同步都是可重新锁定的。
使用示例如下所示。
复制代码就是:
publicclasstestimplementsrunnable {
公共同步语音获取(
system.out.println (thread.current thread ().getId ) );
set (;
}
公共同步语音集(
system.out.println (thread.current thread ().getId ) );
}
@Override
公共void run (}
get (;
}
publicstaticvoidmain (字符串[ ] args ) {
Test ss=new Test (;
新thread (ss ).start );
新thread (ss ).start );
新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);
}
}
}
}
该自旋锁即为可重入锁。