利用同步器实现互斥锁
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); } }
一只船孤独地航行在海上,它既不寻求幸福,也不逃避幸福,它只是向前航行,底下是沉静碧蓝的大海,而头顶是金色的太阳。