本文主要是總結 AQS 的原理,以及 AQS 的使用場景。ide
AQS 的全稱是 AbstractQueuedSynchronizer
的縮寫, 他的本質是一個雙向同步鏈表結構。code
ReentrantLock
、CountDownLatch
、Semaphore
等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(); } } } 複製代碼