[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/Coder994/JavaGuide/patch-1/docs/java/concurrent/aqs.md [Back]  [Original]

---
title:  AQS 
category: Java
tag:
  - Java
---

## AQS 

AQS  `AbstractQueuedSynchronizer`  `java.util.concurrent.locks` 

![](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/Java%20%E7%A8%8B%E5%BA%8F%E5%91%98%E5%BF%85%E5%A4%87%EF%BC%9A%E5%B9%B6%E5%8F%91%E7%9F%A5%E8%AF%86%E7%B3%BB%E7%BB%9F%E6%80%BB%E7%BB%93/AQS.png)

AQS 

```java
public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable {
}
```

AQS  AQS  `ReentrantLock``Semaphore` `ReentrantReadWriteLock``SynchronousQueue` AQS 

## AQS 

 AQS 

### AQS 

AQS  AQS  **CLH ** Craig, Landin, and Hagersten locks 

CLH AQS  CLH Node CLH thread waitStatusprevnext

CLH 

![](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/40cb932a64694262993907ebda6a0bfe~tplv-k3u1fbpfcp-zoom-1.image)

AQS -CLH  [Java AQS -CLH  - Qunar](https://mp.weixin.qq.com/s/jEx-4XhNGOFdCo4Nou5tqg) 

AQS(`AbstractQueuedSynchronizer`)[Java  AQS ](https://www.cnblogs.com/waterystone/p/4920797.html)

![](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/Java%20%E7%A8%8B%E5%BA%8F%E5%91%98%E5%BF%85%E5%A4%87%EF%BC%9A%E5%B9%B6%E5%8F%91%E7%9F%A5%E8%AF%86%E7%B3%BB%E7%BB%9F%E6%80%BB%E7%BB%93/CLH.png)

AQS  **int  `state` ** **** 

`state`  `volatile` 

```java
// volatile
private volatile int state;
```

 `state`  `protected` `getState()``setState()``compareAndSetState()`  `final` 

```java
//
protected final int getState() {
     return state;
}
 // 
protected final void setState(int newState) {
     state = newState;
}
//CASupdateexpect
protected final boolean compareAndSetState(int expect, int update) {
      return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
```

 `ReentrantLock` `state`  0A  `lock()`  `tryAcquire()`  `state+1`  `tryAcquire()`  A  `unlock()`  `state=`0A `state`  state [ ReentrantLock  AQS  - ](./reentrantlock.md)

 `CountDownLatch`  N `state`  N N  N `countDown()` state  CAS(Compare and Swap)  1( `state=0` ) `unpark()`  `await()` 

### AQS 

AQS `Exclusive``ReentrantLock``Share``Semaphore`/`CountDownLatch`

`tryAcquire-tryRelease``tryAcquireShared-tryReleaseShared` AQS `ReentrantReadWriteLock`

### 



1.  `AbstractQueuedSynchronizer` 
2.  AQS 



**AQS  AQS **

```java
//truefalse
protected boolean tryAcquire(int)
//truefalse
protected boolean tryRelease(int)
//0
protected int tryAcquireShared(int)
//truefalse
protected boolean tryReleaseShared(int)
//condition
protected boolean isHeldExclusively()
```

****  `protected` 

[ Java8  yyds!](https://mp.weixin.qq.com/s/zpScSCktFpnSWHWIQem2jg)

AQS  `final` 

## 

 AQS 

### Semaphore()

#### 

`synchronized`  `ReentrantLock` `Semaphore`()

Semaphore  N(N>5)  `Semaphore`  N  5 

```java
// 
final Semaphore semaphore = new Semaphore(5);
// 1
semaphore.acquire();
// 1
semaphore.release();
```

 1 `Semaphore`  

`Semaphore` 

- ****  `acquire()`  FIFO
- **** 

`Semaphore` 

```java
public Semaphore(int permits) {
  	sync = new NonfairSync(permits);
}

public Semaphore(int permits, boolean fair) {
  	sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
```

****

`Semaphore`  Redis +Lua 

#### 

`Semaphore`  AQS  `state`  `permits` `permits` 

`semaphore.acquire()`  `state >= 0`  CAS  `state`  `state=state-1` `state=0` 

```java
// 
public void release() {
  	sync.releaseShared(1);
}

// 
public final boolean releaseShared(int arg) {
    //
    if (tryReleaseShared(arg)) {
      //
      doReleaseShared();
      return true;
    }
    return false;
}
```

#### 

```java
/**
 *
 * @author Snailclimb
 * @date 2018930
 * @Description: 
 */
public class SemaphoreExample1 {
  // 
  private static final int threadCount = 550;

  public static void main(String[] args) throws InterruptedException {
    // 
    ExecutorService threadPool = Executors.newFixedThreadPool(300);
    // 
    final Semaphore semaphore = new Semaphore(20);

    for (int i = 0; i < threadCount; i++) {
      final int threadnum = i;
      threadPool.execute(() -> {// Lambda 
        try {
          semaphore.acquire();// 20/1=20
          test(threadnum);
          semaphore.release();// 
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

      });
    }
    threadPool.shutdown();
    System.out.println("finish");
  }

  public static void test(int threadnum) throws InterruptedException {
    Thread.sleep(1000);// 
    System.out.println("threadnum:" + threadnum);
    Thread.sleep(1000);// 
  }
}
```

 `acquire()`  `release`  `acquire()` `Semaphore`  `Semaphore` 



```java
semaphore.acquire(5);// 520/5=4
test(threadnum);
semaphore.release(5);// 5
```

 `acquire()`  `tryAcquire()`  false

[issue645 ](https://github.com/Snailclimb/JavaGuide/issues/645) 

> `Semaphore`  `CountDownLatch`  AQS  `state`  `permits` `permits` `Park`, `state`  0 `state`  0 , `release()` `release()`  state  1
>  `permits` 

### CountDownLatch 

#### 

`CountDownLatch`  `count` 

`CountDownLatch`  `CountDownLatch` 

#### 

`CountDownLatch` , AQS  `state`  `count` `countDown()` ,`tryReleaseShared` CAS  `state`, `state`  0  `await()`  `state`  0`await()`  `await()` `CountDownLatch`  CAS  `state == 0` `state == 0` `await()` 

#### 

**CountDownLatch ** 

1.  n  :  `CountDownLatch`  n `new CountDownLatch(n)` 1 `countdownlatch.countDown()` 0  `CountDownLatch  await()` 
2.   `CountDownLatch`  1 `new CountDownLatch(1)` `coundownlatch.await()` `countDown()`  0

**CountDownLatch ** 

```java
/**
 *
 * @author SnailClimb
 * @date 2018101
 * @Description: CountDownLatch 
 */
public class CountDownLatchExample1 {
  // 
  private static final int threadCount = 550;

  public static void main(String[] args) throws InterruptedException {
    // 
    ExecutorService threadPool = Executors.newFixedThreadPool(300);
    final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; i++) {
      final int threadnum = i;
      threadPool.execute(() -> {// Lambda 
        try {
          test(threadnum);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } finally {
          countDownLatch.countDown();// 
        }

      });
    }
    countDownLatch.await();
    threadPool.shutdown();
    System.out.println("finish");
  }

  public static void test(int threadnum) throws InterruptedException {
    Thread.sleep(1000);// 
    System.out.println("threadnum:" + threadnum);
    Thread.sleep(1000);// 
  }
}

```

 550 550 `System.out.println("finish");`

 `CountDownLatch`  `CountDownLatch.await()` 

 N  `CountDownLatch`  `CountDownLatch.countDown()` count  1 N  count  0 `await()`

`CountDownLatch`  `await()`  for 

```java
for (int i = 0; i < threadCount-1; i++) {
.......
}
```

 `count`  0

### CyclicBarrier()

#### 

`CyclicBarrier`  `CountDownLatch`  `CountDownLatch`  `CountDownLatch` 

> `CountDownLatch`  AQS  `CycliBarrier`  `ReentrantLock`(`ReentrantLock`  AQS ) `Condition` 

`CyclicBarrier` CyclicBarrier

#### 

`CyclicBarrier`  `count` `count`  `parties`  1 count  0 

```java
//
private final int parties;
//
private int count;
```



1`CyclicBarrier`  `CyclicBarrier(int parties)` `await()`  `CyclicBarrier` 

```java
public CyclicBarrier(int parties) {
    this(parties, null);
}

public CyclicBarrier(int parties, Runnable barrierAction) {
    if (parties  0L)
                        nanos = trip.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    if (g == generation && ! g.broken) {
                        breakBarrier();
                        throw ie;
                    } else {
                        // We're about to finish waiting even if we had not
                        // been interrupted, so this interrupt is deemed to
                        // "belong" to subsequent execution.
                        Thread.currentThread().interrupt();
                    }
                }

                if (g.broken)
                    throw new BrokenBarrierException();

                if (g != generation)
                    return index;

                if (timed && nanos  {
        try {
          test(threadNum);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (BrokenBarrierException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      });
    }
    threadPool.shutdown();
  }

  public static void test(int threadnum) throws InterruptedException, BrokenBarrierException {
    System.out.println("threadnum:" + threadnum + "is ready");
    try {
      /**60*/
      cyclicBarrier.await(60, TimeUnit.SECONDS);
    } catch (Exception e) {
      System.out.println("-----CyclicBarrierException------");
    }
    System.out.println("threadnum:" + threadnum + "is finish");
  }

}
```



```
threadnum:0is ready
threadnum:1is ready
threadnum:2is ready
threadnum:3is ready
threadnum:4is ready
threadnum:4is finish
threadnum:0is finish
threadnum:1is finish
threadnum:2is finish
threadnum:3is finish
threadnum:5is ready
threadnum:6is ready
threadnum:7is ready
threadnum:8is ready
threadnum:9is ready
threadnum:9is finish
threadnum:5is finish
threadnum:8is finish
threadnum:7is finish
threadnum:6is finish
......
```

 5  `await()` 

`CyclicBarrier`  `CyclicBarrier(int parties, Runnable barrierAction)` `barrierAction`

 2

```java
/**
 *
 * @author SnailClimb
 * @date 2018101
 * @Description:  CyclicBarrier  Runnable
 */
public class CyclicBarrierExample2 {
  // 
  private static final int threadCount = 550;
  // 
  private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> {
    System.out.println("------------");
  });

  public static void main(String[] args) throws InterruptedException {
    // 
    ExecutorService threadPool = Executors.newFixedThreadPool(10);

    for (int i = 0; i < threadCount; i++) {
      final int threadNum = i;
      Thread.sleep(1000);
      threadPool.execute(() -> {
        try {
          test(threadNum);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (BrokenBarrierException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      });
    }
    threadPool.shutdown();
  }

  public static void test(int threadnum) throws InterruptedException, BrokenBarrierException {
    System.out.println("threadnum:" + threadnum + "is ready");
    cyclicBarrier.await();
    System.out.println("threadnum:" + threadnum + "is finish");
  }

}
```



```
threadnum:0is ready
threadnum:1is ready
threadnum:2is ready
threadnum:3is ready
threadnum:4is ready
------------
threadnum:4is finish
threadnum:0is finish
threadnum:2is finish
threadnum:1is finish
threadnum:3is finish
threadnum:5is ready
threadnum:6is ready
threadnum:7is ready
threadnum:8is ready
threadnum:9is ready
------------
threadnum:9is finish
threadnum:5is finish
threadnum:6is finish
threadnum:8is finish
threadnum:7is finish
......
```

Web Proxy Viewer  |  New URL  |  Original Page