[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/hello8817/JavaGuide/master/Java/Multithread/AQS.md [Back]  [Original]

****


- [1 AQS ](#1-aqs-)
- [2 AQS ](#2-aqs-)
  - [2.1 AQS ](#21-aqs-)
  - [2.2 AQS ](#22-aqs-)
  - [2.3 AQS](#23-aqs)
- [3 Semaphore\(\)-](#3-semaphore-)
- [4 CountDownLatch ](#4-countdownlatch-)
  - [4.1 CountDownLatch ](#41-countdownlatch-)
  - [4.2 CountDownLatch ](#42-countdownlatch-)
  - [4.3 CountDownLatch ](#43-countdownlatch-)
  - [4.4 CountDownLatch](#44-countdownlatch)
- [5 CyclicBarrier\(\)](#5-cyclicbarrier)
  - [5.1 CyclicBarrier ](#51-cyclicbarrier-)
  - [5.2 CyclicBarrier ](#52-cyclicbarrier-)
  - [5.3 CyclicBarrierCountDownLatch](#53-cyclicbarriercountdownlatch)
- [6 ReentrantLock  ReentrantReadWriteLock](#6-reentrantlock--reentrantreadwritelock)


> AQS;CountDownLatchCyclicBarrier,Semaphore

****

![AQS  AQS ](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-10-31/61115865.jpg)


### 1 AQS 
AQSAbstractQueuedSynchronizerjava.util.concurrent.locks

![enter image description here](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)

AQSAQSReentrantLockSemaphoreReentrantReadWriteLockSynchronousQueueFutureTaskAQSAQS

### 2 AQS 

> AQS

AQS

#### 2.1 AQS 

**AQSAQSCLH**

> CLH(Craig,Landin,and Hagersten)AQSCLHNode

AQS(AbstractQueuedSynchronizer)


![enter image description here](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)

AQSintFIFOAQSCAS

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

protectedgetStatesetStatecompareAndSetState

```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);
}
```

#### 2.2 AQS 

**AQS**

- **Exclusive**ReentrantLock
    - 
    - 
-  **Share**Semaphore/CountDownLatchSemaphoreCountDownLatCh CyclicBarrierReadWriteLock 

ReentrantReadWriteLock ReentrantReadWriteLock

 state /AQS

#### 2.3 AQS



1. AbstractQueuedSynchronizerstate
2. AQS



> `buyTicket()`->`securityCheck()`->`ride()`->`arrive()``ride()` `ride()`

**AQSAQS**

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

```

 `UnsupportedOperationException` AQSfinal  

ReentrantLockstate0Alock()tryAcquire()state+1tryAcquire()Aunlock()state=0Astatestate

CountDownLatchNstateNNNcountDown()stateCAS(Compare and Swap)1(state=0)unpark()await()

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

 AQS 

- http://www.cnblogs.com/waterystone/p/4920797.html
- https://www.cnblogs.com/chengxiao/archive/2017/07/24/7141160.html


### 3 Semaphore()-

**synchronized  ReentrantLock Semaphore()**

```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` acquireSemaphore Semaphore



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

 `acquire``tryAcquire`false


Semaphore 

- **** acquireFIFO
- **** 

**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 

- https://blog.csdn.net/qq_19431333/article/details/70212663

### 4 CountDownLatch 

CountDownLatchJavacountdownlatch

#### 4.1 CountDownLatch 

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

 `CountDownLatch`  1 `new CountDownLatch(1) ` `coundownlatch.await()` countDown() 0

n

#### 4.2 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);// 
  }
}

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

CountDownLatchCountDownLatch.await()

NCountDownLatch CountDownLatch.countDown()count1N count0await()

#### 4.3 CountDownLatch 

CountDownLatchCountDownLatch

#### 4.4 CountDownLatch

CountDownLatch

CountDownLatch CyclicBarrier

CountDownLatch

CountDownLatch 

### 5 CyclicBarrier()

CyclicBarrier  CountDownLatch  CountDownLatch  CountDownLatch 

CyclicBarrier CyclicBarrierCyclicBarrier `CyclicBarrier(int parties)``await` CyclicBarrier 

#### 5.1 CyclicBarrier 

CyclicBarrier ExcelSheetsheetsheetbarrierActionExcel

#### 5.2 CyclicBarrier 

1

```java
/**
 * 
 * @author Snailclimb
 * @date 2018101
 * @Description:  CyclicBarrier  await() 
 */
public class CyclicBarrierExample2 {
  // 
  private static final int threadCount = 550;
  // 
  private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(5);

  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");
    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`

```java
/**
 * 
 * @author SnailClimb
 * @date 2018101
 * @Description:  CyclicBarrier  Runnable
 */
public class CyclicBarrierExample3 {
  // 
  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
......
```
#### 5.3 CyclicBarrierCountDownLatch

CountDownLatchCyclicBarrierresetjdkjavadoc

> CountDownLatch: A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.(CountDownLatch: )
> CyclicBarrier : A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.(CyclicBarrier : )

CountDownLatchNCyclicBarrier

CountDownLatchCyclicBarrier

![CyclicBarrierCountDownLatch](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/AQS333.png)

CyclicBarrierCountDownLatch

- https://blog.csdn.net/u010185262/article/details/54692886
- https://blog.csdn.net/tolcf/article/details/50925145?utm_source=blogxgwz0

### 6 ReentrantLock  ReentrantReadWriteLock

ReentrantLock  synchronized  ReentrantReadWriteLock 

 ReentrantLock  ReentrantReadWriteLock 

- [ReentrantLock  ReentrantReadWriteLock](https://mp.weixin.qq.com/s?__biz=MzU4NDQ4MzU5OA==&mid=2247483745&idx=2&sn=6778ee954a19816310df54ef9a3c2f8a&chksm=fd985700caefde16b9970f5e093b0c140d3121fb3a8458b11871e5e9723c5fd1b5a961fd2228&token=1829606453&lang=zh_CN#rd)

Web Proxy Viewer  |  New URL  |  Original Page