您当前的位置: 首页 > 

Dongguo丶

暂无认证

  • 1浏览

    0关注

    472博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

ReentrantLock源码解析(二)

Dongguo丶 发布时间:2021-09-26 21:29:43 ,浏览量:1

文章目录
  • 可重入原理
    • 加锁
    • 解锁
  • 可打断原理
    • 不可打断模式
    • 可打断模式
  • 条件变量实现原理
    • await流程
      • addConditionWaiter()
      • fullyRelease ()
      • park()
    • signal 流程
      • isHeldExclusively()
      • doSignal ()
      • transferForSignal ()
    • unlock 流程

可重入原理

仍然以非公平锁为例

加锁
/**
 * Performs non-fair tryLock.  tryAcquire is implemented in
 * subclasses, but both need nonfair try for trylock method.
 */
// Sync的方法
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()) {
        //state++
        int nextc = c + acquires;
        if (nextc 0或者cas失败 唤醒Thread-0
        LockSupport.unpark(node.thread);
    return true;
}
private Node enq(final Node node) {
    for (;;) {
        Node t = tail;//此时同步队列尾指针指向的是Thread-3
        if (t == null) { // Must initialize
            if (compareAndSetHead(new Node()))
                tail = head;
        } else {
            node.prev = t;//Thread-0的前指针指向Thread-3
            if (compareAndSetTail(t, node)) {//同步队列尾指针指向Thread-0
                t.next = node;//Thread-3的后指针指向Thread-0
                return t;//返回Thead-3
            }
        }
    }
}

image-20210913200206976

unlock 流程

接着Thread-1 会释放锁,进入 unlock 流程,然后唤醒Thread-2去尝试获取锁

unlock释放锁的流程已经在从ReentrantLock源码解读AQS中讲解过了,这里就不再继续赘述了。

关注
打赏
1638062488
查看更多评论
立即登录/注册

微信扫码登录

0.0416s