> For the complete documentation index, see [llms.txt](https://moluo.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://moluo.gitbook.io/notes/bian-cheng-xue-xi/java/java-gao-bing-fa/7.5j.u.c-zhi-aqsreentrantlock-yu-suo.md).

# 7.5J.U.C值AQS-ReentrantLock与锁

java中的锁主要分两类，一种使用`synchronized关键字修饰的锁`和`JUC提供的锁`

## ReentrantLock(可重入锁)和synchronized的区别

* 可重入性：都是可重入锁，重入一次锁都自加1
* 锁的实现：synchronized依赖于JVM实现，ReentrantLock依赖于JDK实现
* 性能的区别：synchronized再没有优化之前，性能比ReentrantLock差很多。但自从synchronized引入了偏向锁、轻量级锁、自旋锁后，两者的性能就差不多了。ReentrantLock做到在用户态就解决加锁问题，避免进入内核态
* 功能区别：syncronized写法比ReentrantLock更便利，ReentrantLock需要手动生命加锁和释放锁，为了防止锁未释放造成死锁，建议在finally块中释放锁；灵活性和细粒度ReentrantLock优于syncronized

ReentrantLock独有的功能

* 可指定是公平锁还是非公平锁。公平锁是指先等待的线程先获得锁
* 提供了一个Condition类，可以分组唤醒需要唤醒的线程
* 提供能够中断等待锁的线程机制，lock.lockInterruptibly()

当你需要使用到ReentrantLock独有的功能时，就需要使用到ReentrantLock

```java
package com.moluo.concurrency.lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
    public static int clientTotal = 5000;
    public static int threadTotal = 200;
    public static int count = 0;

    private static ReentrantLock lock=new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("count:" + count);
    }

    private static void add() {
        lock.lock();
        try {
            count++;
        }finally {
            lock.unlock();
        }
    }
}
```

## ReentrantReadWriteLock

在没有任何读锁或写锁被持有的时候，才可以获取写锁

不适用于读操作频繁的场景

```java
package com.moluo.concurrency.lock;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockExample {
    public final Map<String, Data> map = new TreeMap<>();

    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();

    public Data get(String key) {
        readLock.lock();
        try {
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public Set<String> getAllKeys() {
        readLock.lock();
        try {
            return map.keySet();
        } finally {
            readLock.unlock();
        }
    }

    public Data put(String key, Data value) {
        writeLock.lock();
        try {
            return map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }


    class Data {

    }
}
```

StampedLock

写、读、和乐观读
