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();
}
}
}
}
网友评论