思路
- 基于AQS实现;
- 仿照JDK里面的ReentrantLock;
- 定义原子变量state,为1代表持有锁,否则不持有锁;
- 支持定义条件变量;
编码如下
public static class NonReentrantLock implements Lock,Serializable {
private static class Sync extends AbstractQueuedSynchronizer {
protected boolean isHeldExclusively() {
return getState() == 1;
}
protected boolean tryAcquire(int acquires) {
if (compareAndSetState(0,1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
protected boolean tryRelease(int acquires) {
if (getState() == 0) {
throw new IllegalMonitorStateException();
}
setExclusiveOwnerThread(null);
setState(0);
return true;
}
Condition newCondition() {
return new ConditionObject();
}
}
private final Sync sync = new Sync();
public void lock() {
sync.acquire(1);
}
public boolean tryLock(int acquires) {
return sync.tryAcquire(1);
}
public boolean tryLock(long timeout, TimeUnit timeUnit) {
return sync.tryAcquireNanos(1, timeUnit.toNanos(timeout));
}
public void unlock() {
sync.release(1);
}
public Condition newCondition() {
return sync.newCondition();
}
public void lockInterruptibly() {
sync.acquireInterruptibly(1);
}
}