1.如果只是當前線程自己使用遞歸鎖,沒有完全配對上鎖解鎖,可以正常運行,但如果還有別的線程則會引發問題,最好上鎖和解鎖配對使用。
下面例子演示 ,t1線程故意內層不釋放鎖,引起t2線程阻塞。代碼如下:
public class SynclockDemo { public static void main(String[ ]args) { Lock lock = new ReentrantLock(); new Thread(() -> { try { lock.lock(); System.out.println(Thread.currentThread().getName() +" 外層"); try { lock.lock(); System.out.println(Thread.currentThread().getName() +" 內層"); } finally { //故意不釋放鎖觀察t2線程是否正常運行,結果t2線程一直阻塞 // lock.unlock(); } } finally { lock.unlock(); } },"t1").start(); new Thread(() -> { lock.lock(); System.out.println(Thread.currentThread().getName() +"外層"); lock.unlock(); },"t2").start(); } }
結果: t2線程一直阻塞,原因t1線程未正常上鎖解鎖(上鎖2次解鎖1次)。
總結:
必須配對上鎖解鎖過程,否則會引發各種錯誤。