1.是个What
可重入锁,也叫做递归锁,指的是同一个线程T在进入外层函数A获得锁L之后,T继续进入内层递归函数B时,仍然有获取该锁L的代码,在不释放锁L的情况下,可以重复获取该锁L。
非可重入锁,也叫做自旋锁,对比上面,指的是同一个线程T在进入外层函数A获得锁L之后,T继续进入内层递归函数B时,仍然有获取该锁L的代码,必须要先释放进入函数A的锁L,才可以获取进入函数B的锁L。
2.来个Demo
2.1 非可重入锁:
public class UnReentrantLock {
private boolean isLocked = false;
public synchronized void lock() throws InterruptedException {
while (isLocked) {
wait();
}
isLocked = true;
}
public synchronized void unlock() {
isLocked = false;
notify();
}
}
public class Count {
UnReentrantLock lock = new UnReentrantLock();
public void outer() throws InterruptedException {
lock.lock();
inner();
lock.unlock();
}
public void inner() throws InterruptedException {
lock.lock();
System.out.println("call inner");
lock.unlock();
}
}
public class LockTest {
@Test
public void testUnReentrantLock() throws InterruptedException {
Count count = new Count();
//在调用inner()时,因为没有释放锁,再次获取锁,会发生死锁
count.print();
}
}
2.2 可重入锁
public class Lock{
boolean isLocked = false;
Thread lockedBy = null;
int lockedCount = 0;
public synchronized void lock()
throws InterruptedException{
Thread callingThread = Thread.currentThread();
while(isLocked && lockedBy != callingThread){
wait();
}
isLocked = true;
lockedCount++;
lockedBy = callingThread;
}
public synchronized void unlock(){
if(Thread.curentThread() == this.lockedBy){
lockedCount--;
if(lockedCount == 0){
isLocked = false;
notify();
}
}
}
}
可重入锁是使用持有锁的线程对象和锁计数来实现的,非可重入锁相当于判断条件只有锁计数,而且锁计数<=1。
2.java中的可重入锁
ReentrantLock 、synchronized等
3.干嘛搞个这货
可重入锁可以防止死锁。
网友评论