Java可重入锁

2020-02-01  本文已影响0人  粑粑八成
class Lock {

  private boolean isLocked = false;
  private Thread lockedBy = null; // 存储线程
  private int holdCount = 0;

  // 使用锁
  public synchronized void lock() throws InterruptedException {
    Thread t = Thread.currentThread();
    while (isLocked && lockedBy != t) {
      wait();
    }
    isLocked = true;
    lockedBy = t;
    holdCount++;
  }

  // 释放锁
  public synchronized void unLock() {
    if (lockedBy == Thread.currentThread()) {
      holdCount--;
      if (holdCount == 0) {
        isLocked = false;
        lockedBy = null;
        notify();
      }
    }
  }
}
上一篇下一篇

猜你喜欢

热点阅读