ReentrantLock reentrantLock=new ReentrantLock(true);
reentrantLock.lock();
reentrantLock.unlock();

1 reentrantLock.lock() 内部实现
final void lock() {
    acquire(1);
}

2 acquire(1) 内部实现:

public final void acquire(int arg) {
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}

3 tryAcquire 内部实现

protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
        if (!hasQueuedPredecessors() &&
            compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0)
            throw new Error(\"Maximum lock count exceeded\");
        setState(nextc);
        return true;
    }
    return false;
}

public final boolean hasQueuedPredecessors() {
    // The correctness of this depends on head being initialized
    // before tail and on head.next being accurate if the current
    // thread is first in queue.
    Node t = tail; // Read fields in reverse initialization order
    Node h = head;
    Node s;
    return h != t &&
        ((s = h.next) == null || s.thread != Thread.currentThread());
}

5 acquireQueued 内部实现

final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        boolean interrupted = false;
        for (;;) {
            final Node p = node.predecessor();
            if (p == head && tryAcquire(arg)) {
                setHead(node);
                p.next = null; // help GC
                failed = false;
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}

解锁的 内部实现:


1 public final boolean release(int arg) {
    if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h);
        return true;
    }
    return false;
}
 2 protected final boolean tryRelease(int releases) {
    int c = getState() - releases;
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    if (c == 0) {
        free = true;
        setExclusiveOwnerThread(null);
    }
    setState(c);
    return free;
}

 

 

总结 :

公平锁和非公平锁 的区别 只是 在加锁的时候,解锁的时候逻辑是一样的,公平锁在获取锁的时候 少两个逻辑 。

非公平锁获取锁的步骤:

1   尝试抢占锁

2   如果获取失败了,再次判断锁的标志位是否为0 ,如果是 ,再次直接尝试抢占锁

3   如果不是把线程放入队列,再次判断当前节点前是否只有一个节点,如果是 ,再次尝试获取锁,否则 更改节点阻塞状态, 阻塞线程。

公平锁 获取锁的步骤  : 

1  不尝试抢占锁

2  判断锁的标志位是否为0,如果为 0,不直接抢占锁  而是判断是否有前置节点,如果有则不获取锁,如果没有在获取锁。

3 如果不是0 则 把线程放入队列,再次判断当前节点前是否只有一个节点,如果是 ,再次尝试获取锁,否则 更改节点阻塞状态, 阻塞线程。

 

对比可以看出 1 ,2 两个步骤之间的区别,公平锁,在极力避免抢占锁,而非公平锁,则在极力抢占锁。

 

 

 

 

 

收藏 打印