编程语言
首页 > 编程语言> > ReentrantLock源码之公平锁的实现

ReentrantLock源码之公平锁的实现

作者:互联网

public class ReentrantLockDemo {

    public static void main(String[] args) {
        ReentrantLock reentrantLock = new ReentrantLock(true);
        reentrantLock.lock();
        reentrantLock.unlock();
    }

}
    public ReentrantLock() {
        sync = new NonfairSync();    // new了1个非公平实现
    }
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();    // 为true时返回公平实现,否则返回非公平实现
    }

public class ReentrantLockDemo {

    public static void main(String[] args) {
        ReentrantLock reentrantLock = new ReentrantLock(true);
        reentrantLock.lock();
        reentrantLock.unlock();
    }

}

public void lock() {
    sync.acquire(1);
}

public final void acquire(int arg) {
    // 尝试获取锁
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))    // 同时获取队列失败
        selfInterrupt();      // 则线程终止
}
    protected boolean tryAcquire(int arg) {
        throw new UnsupportedOperationException();
    }
static final class NonfairSync extends Sync {
    private static final long serialVersionUID = 7316153563782823691L;
    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}

@ReservedStackAccess
final boolean nonfairTryAcquire(int acquires) {
    final Thread current = Thread.currentThread();    // 获取当前线程
    int c = getState();    // 获取状态
    if (c == 0) {    // 当前没有线程获取到这个锁
        if (compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;    // 获得锁
        }
    }
    else if (current == getExclusiveOwnerThread()) {    // 是否是持有锁的线程,即重入状态
        int nextc = c + acquires;    // 重入状态加1
        if (nextc < 0) // overflow      // 超过最大重入状态,抛出异常
            throw new Error("Maximum lock count exceeded");
        setState(nextc);    // 更新
        return true;    // 获得锁
    }
    return false;
}
    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
    private Node addWaiter(Node mode) {
        Node node = new Node(mode);    // 传入参数,当前线程,new1个Node

        for (;;) {
            Node oldTail = tail;    // 前置节点指向尾节点
            if (oldTail != null) {
                node.setPrevRelaxed(oldTail);
                if (compareAndSetTail(oldTail, node)) {    // node设置为尾节点
                    oldTail.next = node;
                    return node;
                }
            } else {
                initializeSyncQueue();    // 若整条队列为null,执行入队
            }
        }
    }
Node(Node nextWaiter) {
    this.nextWaiter = nextWaiter;
    THREAD.set(this, Thread.currentThread());
}

标签:Node,查看,ReentrantLock,源码,公平,arg,new,public
来源: https://www.cnblogs.com/chniny/p/16269335.html