可重入锁,持有锁的线程可以进入任何锁所同步的代码块
不可重入锁:
public class Lock { private boolean isLock = false; /** * 同步方法 */ public synchronized void lock() throws InterruptedException { if (isLock) { wait(); } isLock = true; } // 不能保证我加的锁是我释放的,也就是不能保证一致性 public synchronized void unLock() { isLock = false; notify(); } }
可重入锁
public class Lock { private boolean isLock = false; private Thread lockedThread; private int lockCount; public synchronized void lock() throws InterruptedException { Thread currentThread = Thread.currentThread(); while (isLock && lockedThread != currentThread) { wait(); } isLock = true; lockedThread = currentThread; lockCount++; } public synchronized void unLock() { Thread currentThread = Thread.currentThread(); // 我的锁只能我来释放,一致性 if (lockedThread == currentThread) { lockCount--; if (lockCount == 0) { isLock = false; lockedThread = null; } notify(); } }
测试:
public class LockTest { private Lock lock = new Lock(); private void lockMethod1() throws InterruptedException { lock.lock(); // 进入当前锁所同步的代码块,可重入锁不用等待直接获取锁,不可重入锁需要重新获取锁 lockMethod2(); lock.unLock(); } private void lockMethod2() throws InterruptedException { lock.lock(); // doSomeThing lock.unLock(); } }