package test; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; /** * 互斥锁 * */ public class Mutex implements Lock { /** * 自定义同步器,通过继承AbstractQueuedSynchronizer来管理同步状态 * 同步器是实现锁的关键,在锁的实现中聚合同步器,利用同步器实现锁的语义 锁是面向使用者的,定义了使用者与锁交互的接口,隐藏了实现细节 * 同步器是面向锁的实现者,它简化了锁的实现方式,屏蔽了同步状态管理、线程的排队、等待与唤醒等底层操作 锁和同步器很好地隔离了使用者与实现者所需要关注的领域 * */ private static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 1L; // 是否处于占用状态 @Override protected boolean isHeldExclusively() { return getState() == 1; } // 当状态为零的时候获取锁 @Override public boolean tryAcquire(int acquire) { if (compareAndSetState(0, 1)) { setExclusiveOwnerThread(Thread.currentThread()); return true; } return false; } // 释放锁,将状态设置为0 @Override protected boolean tryRelease(int release) { if (getState() == 0) throw new IllegalMonitorStateException(); setExclusiveOwnerThread(null); setState(0); return true; } Condition newCondition() { return new ConditionObject(); } } // 仅需要将操作代理到sync上即可 private final Sync sync = new Sync(); @Override public void lock() { sync.acquire(1); } @Override public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } @Override public Condition newCondition() { return sync.newCondition(); } @Override public boolean tryLock() { return sync.tryAcquire(1); } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(time)); } @Override public void unlock() { sync.release(1); } }
原文:https://www.cnblogs.com/archer-wen/p/12099093.html