美文网首页
Java可重入锁

Java可重入锁

作者: 粑粑八成 | 来源:发表于2020-02-01 15:32 被阅读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();
          }
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:Java可重入锁

          本文链接:https://www.haomeiwen.com/subject/pvhxxhtx.html