AQS(一)简介和使用

发布时间:2026/7/28 15:10:55

AQS(一)简介和使用 1、AQS简介AQS(AbstractQueuedSynchronizer)即队列同步器。是用来构建锁或者其他同步组件的基础框架JUC包下的ReentrantLock、Semaphore、ReentrantReadWriteLock、CountDownLatch、SynchronousQueue和FutureTask等这些阻塞类有一个共同点就是都是基于AQS构建的。锁是面向使用者它定义了使用者与锁交互的接口隐藏了实现细节同步器是面向锁的实现者它简化了锁的实现方式屏蔽了同步状态的管理线程的排队等待和唤醒等底层操作。AQS的主要使用方式是继承实现同步组件时推荐定义继承AQS的静态内存类并重写需要的protected修饰的方法AQS使用一个int类型的成员变量state来表示同步状态当state0时表示已经获取锁当state0时表示释放了锁。AQS提供了三个方法来对同步状态state进行操作。2、AQS的设计模式模板方法AQS的设计是使用模板方法设计模式它将一些方法开放给子类进行重写而同步器给同步组件所提供模板方法又会重新调用被子类所重写的方法示例AQS中需要重写的方法tryAcquireprotected boolean tryAcquire(int arg) { throw new UnsupportedOperationException(); }ReentrantLock中NonfairSync继承AQS会重写该方法为protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); }而AQS中的模板方法acquire():public final void acquire(int arg) { if (!tryAcquire(arg) acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }acquire会调用tryAcquire方法而此时当继承AQS的NonfairSync调用模板方法acquire时就会调用已经被NonfairSync重写的tryAcquire方法。这就是使用AQS的方式。3、AQS源码中的示例class Mutex implements Lock, java.io.Serializable { // 继承AQS的静态内存类 // 重写方法 private static class Sync extends AbstractQueuedSynchronizer { // Reports whether in locked state protected boolean isHeldExclusively() { return getState() 1; } public boolean tryAcquire(int acquires) { assert acquires 1; // Otherwise unused if (compareAndSetState(0, 1)) { setExclusiveOwnerThread(Thread.currentThread()); return true; } return false; } // Releases the lock by setting state to zero protected boolean tryRelease(int releases) { assert releases 1; // Otherwise unused if (getState() 0) throw new IllegalMonitorStateException(); setExclusiveOwnerThread(null); setState(0); return true; } // Provides a Condition Condition newCondition() { return new ConditionObject(); } // Deserializes properly private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); setState(0); // reset to unlocked state } } private final Sync sync new Sync(); //使用同步器的模板方法实现自己的同步语义 public void lock() { sync.acquire(1); } public boolean tryLock() { return sync.tryAcquire(1); } public void unlock() { sync.release(1); } public Condition newCondition() { return sync.newCondition(); } public boolean isLocked() { return sync.isHeldExclusively(); } public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } } public class MutextDemo { private static Mutex mutex new Mutex(); public static void main(String[] args) { for (int i 0; i 10; i) { Thread thread new Thread(() - { mutex.lock(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } finally { mutex.unlock(); } }); thread.start(); } } }

相关新闻