基于AQS实现自定义不可重入的独占锁

思路

  1. 基于AQS实现;
  2. 仿照JDK里面的ReentrantLock;
  3. 定义原子变量state,为1代表持有锁,否则不持有锁;
  4. 支持定义条件变量;

编码如下

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);
	}
}
posted @ 2021-07-07 19:25  咸与维新  阅读(50)  评论(0)    收藏  举报