AQS 处理流程和使用

742 阅读1分钟

概述

本文主要是总结 AQS 的原理,以及 AQS 的使用场景。

什么是 AQS?

AQS 的全称是 AbstractQueuedSynchronizer 的缩写, 他的本质是一个双向同步链表结构。

  • 使用场景 ReentrantLockCountDownLatchSemaphore

ReentrantLock 使用 Demo

public class ReentrantLockTest {

    ReentrantLock lock = new ReentrantLock();


    public static void main(String[] args) {
        ReentrantLockTest test = new ReentrantLockTest();

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 3; i++) {
            executorService.submit(test::serviceMethod);
        }
        executorService.shutdown();
        while (true) {
            if (executorService.isTerminated()) {
                break;
            }

        }
    }

    private void serviceMethod() {
        lock.lock();
        doSomething();
        lock.unlock();
    }

    private static void doSomething() {
        try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

AQS 的处理流程