可重入锁的设计目的是为了防止死锁。例如在多个方法互相调用的场景,需要保证可重入,不然很容易死锁。
java中的synchronized和ReentrantLock都是可重入锁,只限同一个线程,子线程也不可以。
public static void main(String[] args) {
TestLock testLock = new TestLock();
testLock.methodA();
}
public synchronized void methodA(){
System.out.println("methodA invoked");
methodB();
}
public void methodB(){
synchronized (this){
System.out.println("methodB invoked");
}
}