Ch7-Java Lock 之 ReentrantLock

Ch7-Java Lock 之 ReentrantLock

January 15, 2020
Java | JUC
java

java.util.concurrent.locks.ReentrantLock

1. 重要变量 #

ReentrantLock 中的 Sync 继承自 AQS,因此其临界资源为 AQS 中的 state 变量。ReentrantLock 将 state 定义为加锁次数(当然也包括重入次数)。

2. 核心接口 #

public class ReentrantLock implements Lock, java.io.Serializable {
    abstract static class Sync extends AbstractQueuedSynchronizer {
        abstract void lock();
        protected final boolean tryRelease(int releases);
    }

    static final class NonfairSync extends Sync {
        final void lock();
        protected final boolean tryAcquire(int acquires);
    }

    static final class FairSync extends Sync {
        final void lock();
        protected final boolean tryAcquire(int acquires);
    }

    public void lock() {sync.lock();}
    public void unlock() {sync.release(1);}
}