当前位置: 移动技术网 > IT编程>开发语言>Java > 并发编程(五)——AbstractQueuedSynchronizer 之 ReentrantLock源码分析

并发编程(五)——AbstractQueuedSynchronizer 之 ReentrantLock源码分析

2018年12月26日  | 移动技术网IT编程  | 我要评论

本文将从 reentrantlock 的公平锁源码出发,分析下 abstractqueuedsynchronizer 这个类是怎么工作的,希望能给大家提供一些简单的帮助。

aqs 结构

先来看看 aqs 有哪些属性,搞清楚这些基本就知道 aqs 是什么套路了!

// 头结点,你直接把它当做 当前持有锁的线程 
private transient volatile node head;
// 阻塞的尾节点,每个新的节点进来,都插入到最后,也就形成了一个隐视的链表
private transient volatile node tail;
// 这个是最重要的,不过也是最简单的,代表当前锁的状态,0代表没有被占用,大于0代表有线程持有当前锁
// 之所以说大于0,而不是等于1,是因为锁可以重入嘛,每次重入都加上1
private volatile int state;
// 代表当前持有独占锁的线程,举个最重要的使用例子,因为锁可以重入
// reentrantlock.lock()可以嵌套调用多次,所以每次用这个来判断当前线程是否已经拥有了锁
// if (currentthread == getexclusiveownerthread()) {state++}
private transient thread exclusiveownerthread; //继承自abstractownablesynchronizer

abstractqueuedsynchronizer 的等待队列示意如下所示,注意了,之后分析过程中所说的 queue,也就是阻塞队列不包含 head,因为head表示当前持有锁的线程,并没有在等待获取锁。

等待队列中每个线程被包装成一个 node,数据结构是链表,一起看看源码吧:

static final class node {
    /** marker to indicate a node is waiting in shared mode */
    // 标识节点当前在共享模式下
    static final node shared = new node();
    /** marker to indicate a node is waiting in exclusive mode */
    // 标识节点当前在独占模式下
    static final node exclusive = null;

    // ======== 下面的几个int常量是给waitstatus用的 ===========
    /** waitstatus value to indicate thread has cancelled */
    // 代码此线程取消了争抢这个锁
    static final int cancelled =  1;
    /** waitstatus value to indicate successor's thread needs unparking */
    // 官方的描述是,其表示当前node的后继节点对应的线程需要被唤醒
    static final int signal    = -1;
    /** waitstatus value to indicate thread is waiting on condition */
    // 本文不分析condition,所以略过吧,下一篇文章会介绍这个
    static final int condition = -2;
    /**
     * waitstatus value to indicate the next acquireshared should
     * unconditionally propagate
     */
    // 同样的不分析,略过吧
    static final int propagate = -3;
    // =====================================================

    // 取值为上面的1、-1、-2、-3,或者0(以后会讲到)
    // 这么理解,暂时只需要知道如果这个值 大于0 代表此线程取消了等待,
    // 也许就是说半天抢不到锁,不抢了,reentrantlock是可以指定timeouot的。。。
    volatile int waitstatus;
    // 前驱节点的引用
    volatile node prev;
    // 后继节点的引用
    volatile node next;
    // 这个就是线程本尊
    volatile thread thread;
    // 这个是在condition中用来构建单向链表,同样下一篇文章中介绍
    node nextwaiter;

}

node 的数据结构其实也挺简单的,就是 thread + waitstatus + pre + next 四个属性而已,如果大家对linkedlist熟悉的话,那就更简单了,如果想了解linkedlist,可以看看我前面的文章jdk1.8源码(二)——java.util.linkedlist

下面,我们开始说 reentrantlock 的公平锁,首先,我们先看下 reentrantlock 的使用方式。

// 我用个web开发中的service概念吧
public class orderservice {
    // 使用static,这样每个线程拿到的是同一把锁
    private static reentrantlock reentrantlock = new reentrantlock(true);

    public void createorder() {
        // 比如我们同一时间,只允许一个线程创建订单
        reentrantlock.lock();
        // 通常,lock 之后紧跟着 try 语句
        try {
            // 这块代码同一时间只能有一个线程进来(获取到锁的线程),
            // 其他的线程在lock()方法上阻塞,等待获取到锁,再进来
            // 执行代码...
        } finally {
            // 释放锁
            // 释放锁必须要在finally里,确保锁一定会被释放,如果写在try里面,发生异常,则有可能不会执行,就会发生死锁
            reentrantlock.unlock();
        }
    }
}

reentrantlock 在内部用了内部类 sync 来管理锁,所以真正的获取锁和释放锁是由 sync 的实现类来控制的。

abstract static class sync extends abstractqueuedsynchronizer {

}

sync 有两个实现,分别为 nonfairsync(非公平锁)和 fairsync(公平锁)

公平锁:每个线程抢占锁的顺序为先后调用lock方法的顺序依次获取锁,类似于排队吃饭。

非公平锁:每个线程抢占锁的顺序不定,谁运气好,谁就获取到锁,和调用lock方法的先后顺序无关。

我们看 fairsync 部分。

public reentrantlock(boolean fair) {
    sync = fair ? new fairsync() : new nonfairsync();
}

线程抢锁

我们来看看lock方法的实现

 1 static final class fairsync extends sync {
 2     private static final long serialversionuid = -3000897897090466540l;
 3       // 争锁
 4     final void lock() {
 5         acquire(1);
 6     }
 7     // 来自父类aqs,我直接贴过来这边
 8     // 如果tryacquire(arg) 返回true,表示尝试获取锁成功,获取到锁,也就结束了。
 9     // 否则,acquirequeued方法会将线程压到队列中
10     public final void acquire(int arg) { // 此时 arg == 1
11         // 首先调用tryacquire(1)一下,名字上就知道,这个只是试一试
12         // 因为有可能直接就成功了呢,也就不需要进队列排队了
13         if (!tryacquire(arg) &&
14             // tryacquire(arg)没有成功,这个时候需要把当前线程挂起,放到阻塞队列中。
15             acquirequeued(addwaiter(node.exclusive), arg)) {
16               selfinterrupt();
17         }
18     }
19     //先看下tryacquire方法:使用protected修饰,留空了,是想留给子类去实现
20     protected boolean tryacquire(int arg) {
21         throw new unsupportedoperationexception();
22     }
23     
24     //看fairsync的tryacquire方法:
25     // 尝试直接获取锁,返回值是boolean,代表是否获取到锁
26     // 返回true:1.没有线程在等待锁;2.重入锁,线程本来就持有锁,也就可以理所当然可以直接获取
27     protected final boolean tryacquire(int acquires) {
28         final thread current = thread.currentthread();
29         int c = getstate();
30         // state == 0 此时此刻没有线程持有锁
31         if (c == 0) {
32             // 虽然此时此刻锁是可以用的,但是这是公平锁,既然是公平,就得讲究先来后到,
33             // 看看有没有别人在队列中等了半天了,如果在队列中有等待的线程,则这里就不能获取到锁
34             if (!hasqueuedpredecessors() &&
35                 // 如果没有线程在等待,那就用cas尝试一下,尝试将state的状态从0改成1,成功了就获取到锁了,
36                 // 不成功的话,只能说明一个问题,就在刚刚几乎同一时刻有个线程抢先了
37                 // 有其他线程同时进入到了这一步,并且执行cas改变state状态成功
38                 compareandsetstate(0, acquires)) {
39                 // 到这里就是获取到锁了,标记一下,告诉大家,现在是我占用了锁
40                 setexclusiveownerthread(current);
41                 return true;
42             }
43         }
44           // 会进入这个else if分支,说明是重入了,需要操作:state=state+1
45         else if (current == getexclusiveownerthread()) {
46             int nextc = c + acquires;
47             if (nextc < 0)
48                 throw new error("maximum lock count exceeded");
49             setstate(nextc);
50             return true;
51         }
52         // 如果到这里,说明前面的if和else if都没有返回true,说明没有获取到锁
53         return false;
54     }
55 }

 我们来看看 tryacquire 里面的几个方法

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;
    //如果队列中有等待的线程,则返回true,否则返回false
    return h != t &&
        ((s = h.next) == null || s.thread != thread.currentthread());
}
//我们看看第38行cas改变state状态的方法 
//compareandsetstate(0, acquires)) acquires=1

protected final boolean compareandsetstate(int expect, int update) {
    // see below for intrinsics setup to support this
    //此处调用了sun.misc.unsafe类方法进行cas操作
    //this表示abstractqueuedsynchronizer对象,stateoffset表示state的偏移量,expect此时为0,update为1
    //此方法表示比较state的stateoffset处内存位置中的值和期望的值,如果相同则更新。
    //此时表示把state的值从0改为1,成功返回true;但是同时有可能其他线程也来修改了state的值,已经不为0了,则返回false
    return unsafe.compareandswapint(this, stateoffset, expect, update);
}

private static final unsafe unsafe = unsafe.getunsafe();
//abstractqueuedsynchronizer中state属性的偏移量
private static final long stateoffset;
//abstractqueuedsynchronizer中head属性的偏移量,后面以此类推
private static final long headoffset;
private static final long tailoffset;
private static final long waitstatusoffset;
private static final long nextoffset;

static {
    try {
        //在类加载的时候会通过sun.misc.unsafe类方法获取abstractqueuedsynchronizer中各个属性的偏移量,方便后面各种cas操作
        stateoffset = unsafe.objectfieldoffset
            (abstractqueuedsynchronizer.class.getdeclaredfield("state"));
        headoffset = unsafe.objectfieldoffset
            (abstractqueuedsynchronizer.class.getdeclaredfield("head"));
        tailoffset = unsafe.objectfieldoffset
            (abstractqueuedsynchronizer.class.getdeclaredfield("tail"));
        waitstatusoffset = unsafe.objectfieldoffset
            (node.class.getdeclaredfield("waitstatus"));
        nextoffset = unsafe.objectfieldoffset
            (node.class.getdeclaredfield("next"));

    } catch (exception ex) { throw new error(ex); }
}
    
/**
* 比较obj的offset处内存位置中的值和期望的值,如果相同则更新。此更新是不可中断的。
* 
* @param obj 需要更新的对象
* @param offset obj中整型field的偏移量
* @param expect 希望field中存在的值
* @param update 如果期望值expect与field的当前值相同,设置filed的值为这个新值
* @return 如果field的值被更改返回true
*/
public native boolean compareandswapint(object obj, long offset, int expect, int update);

//等待队列里没有线程等待,并且cas改变state成功,则进入第40行代码 setexclusiveownerthread(current);
protected final void setexclusiveownerthread(thread thread) {
    //就是对exclusiveownerthread赋值
    exclusiveownerthread = thread;
}

由此我们清楚了tryacquire(arg)方法的作用,就是改变把state的状态改为1或者加1,并将 exclusiveownerthread 赋值为当前线程,如果获取锁成功,则lock()方法结束,主线程里面的业务代码继续往下执行。

如果不tryacquire(arg)返回false,则要执行 acquirequeued(addwaiter(node.exclusive), arg)),将当前线程挂起,放到阻塞队列中

这个方法,首先需要执行:addwaiter(node.exclusive)

  1 /**
  2  * creates and enqueues node for current thread and given mode.
  3  *
  4  * @param mode node.exclusive for exclusive, node.shared for shared
  5  * @return the new node
  6  */
  7 // 此方法的作用是把线程包装成node,同时进入到队列中
  8 // 参数mode此时是node.exclusive,代表独占模式
  9 private node addwaiter(node mode) {
 10     node node = new node(thread.currentthread(), mode);
 11     // try the fast path of enq; backup to full enq on failure
 12     // 以下几行代码想把当前node加到链表的最后面去,也就是进到阻塞队列的最后
 13     node pred = tail;
 14 
 15     // tail!=null => 队列不为空
 16     if (pred != null) { 
 17         // 设置自己的前驱 为当前的队尾节点
 18         node.prev = pred; 
 19         // 用cas把自己设置为队尾,就是更新tail的值,pred表示tail原始值,node表示期望更新的值, 如果成功后,tail == node了
 20         if (compareandsettail(pred, node)) { 
 21             // 进到这里说明设置成功,当前node==tail, 将自己与之前的队尾相连
 22             // 上面已经有 node.prev = pred
 23             // 加上下面这句,也就实现了和之前的尾节点双向连接了
 24             // pred为临时变量,表示之前的队尾节点,现在将队尾节点的next指向node,则将node添加到队尾了
 25             pred.next = node;
 26             // 线程入队了,可以返回了
 27             return node;
 28         }
 29     }
 30     // 仔细看看上面的代码,如果会到这里,
 31     // 说明 pred==null(队列是空的) 或者 cas失败(有线程在竞争入队)
 32     enq(node);
 33     return node;
 34 }
 35 
 36 /**
 37  * inserts node into queue, initializing if necessary. see picture above.
 38  * @param node the node to insert
 39  * @return node's predecessor
 40  */
 41 // 采用自旋的方式入队
 42 // 之前说过,到这个方法只有两种可能:等待队列为空,或者有线程竞争入队,
 43 // 自旋在这边的语义是:cas设置tail过程中,竞争一次竞争不到,我就多次竞争,总会排到的
 44 private node enq(final node node) {
 45     for (;;) {
 46         node t = tail;
 47         // 之前说过,队列为空也会进来这里
 48         if (t == null) { // must initialize
 49             // 初始化head节点
 50             // 还是一步cas,你懂的,现在可能是很多线程同时进来呢
 51             if (compareandsethead(new node()))
 52                 // 给后面用:这个时候head节点的waitstatus==0
 53                 // 这个时候有了head,但是tail还是null,设置一下,
 54                 // 注意:这里只是设置了tail=head,这里还没return
 55                 // 所以,设置完了以后,继续for循环,下次就到下面的else分支了
 56                 tail = head;
 57         } else {
 58             // 下面几行,和上一个方法 addwaiter 是一样的,
 59             // 只是这个套在无限循环里,反正就是将当前线程排到队尾,有线程竞争的话排不上重复排
 60             node.prev = t;
 61             if (compareandsettail(t, node)) {
 62                 t.next = node;
 63                 return t;
 64             }
 65         }
 66     }
 67 }
 68 
 69 
 70 // 现在,又回到这段代码了
 71 // if (!tryacquire(arg) 
 72 //        && acquirequeued(addwaiter(node.exclusive), arg)) 
 73 //     selfinterrupt();
 74 
 75 // 下面这个方法,参数node,经过addwaiter(node.exclusive),此时已经进入阻塞队列
 76 // 注意一下:如果acquirequeued(addwaiter(node.exclusive), arg))返回true的话,
 77 // 意味着上面这段代码将进入selfinterrupt(),所以正常情况下,下面应该返回false
 78 // 这个方法非常重要,应该说真正的线程挂起,然后被唤醒后去获取锁,都在这个方法里了
 79 final boolean acquirequeued(final node node, int arg) {
 80     boolean failed = true;
 81     try {
 82         boolean interrupted = false;
 83         for (;;) {
 84             //获取node的prev节点(node的上一个节点)
 85             final node p = node.predecessor();
 86             // p == head 说明当前节点虽然进到了阻塞队列,但是是阻塞队列的第一个,因为它的前驱是head
 87             // 注意,阻塞队列不包含head节点,head一般指的是占有锁的线程,head后面的才称为阻塞队列
 88             // 所以当前节点可以去试抢一下锁
 89             // 这里我们说一下,为什么可以去试试:
 90             // 首先,它是队头,这个是第一个条件,其次,当前的head有可能是刚刚初始化的node,
 91             // enq(node) 方法里面有提到,head是延时初始化的,而且new node()的时候没有设置任何线程
 92             // 也就是说,当前的head不属于任何一个线程,所以作为队头,可以去试一试,
 93             // tryacquire已经分析过了, 忘记了请往前看一下,就是简单用cas试操作一下state
 94             if (p == head && tryacquire(arg)) {
 95                 //到这里说明刚加入到等待队列里面的node只有一个,并且此时获取锁成功,设置head为node
 96                 sethead(node);
 97                 //将之前的head的next设为null方便jvm垃圾回收
 98                 p.next = null; // help gc
 99                 failed = false;
100                 //此时interrupted = false;
101                 return interrupted;
102             }
103             // 到这里,说明上面的if分支没有成功,要么当前node本来就不是队头,
104             // 要么就是tryacquire(arg)没有抢赢别人,继续往下看
105             if (shouldparkafterfailedacquire(p, node) &&
106                 parkandcheckinterrupt())
107                 interrupted = true;
108         }
109     } finally {
110         if (failed)
111             cancelacquire(node);
112     }
113 }
114 
115 /**
116  * checks and updates status for a node that failed to acquire.
117  * returns true if thread should block. this is the main signal
118  * control in all acquire loops.  requires that pred == node.prev
119  *
120  * @param pred node's predecessor holding status
121  * @param node the node
122  * @return {@code true} if thread should block
123  */
124 // 刚刚说过,会到这里就是没有抢到锁呗,这个方法说的是:"当前线程没有抢到锁,是否需要挂起当前线程?"
125 // 第一个参数是前驱节点,第二个参数才是代表当前线程的节点
126 private static boolean shouldparkafterfailedacquire(node pred, node node) {
127     int ws = pred.waitstatus;
128     // 前驱节点的 waitstatus == -1 ,说明前驱节点状态正常,当前线程需要挂起,直接可以返回true
129     if (ws == node.signal)
130         /*
131          * this node has already set status asking a release
132          * to signal it, so it can safely park.
133          */
134         return true;
135 
136     // 前驱节点 waitstatus大于0 ,之前说过,大于0 说明前驱节点取消了排队。这里需要知道这点:
137     // 进入阻塞队列排队的线程会被挂起,而唤醒的操作是由前驱节点完成的。
138     // 所以下面这块代码说的是将当前节点的prev指向waitstatus<=0的节点,
139     // 简单说,如果前驱节点取消了排队,
140     // 找前驱节点的前驱节,往前循环总能找到一个waitstatus<=0的节点
141     if (ws > 0) {
142         /*
143          * predecessor was cancelled. skip over predecessors and
144          * indicate retry.
145          */
146         do {
147             node.prev = pred = pred.prev;
148         } while (pred.waitstatus > 0);
149         pred.next = node;
150     } else {
151         /*
152          * waitstatus must be 0 or propagate.  indicate that we
153          * need a signal, but don't park yet.  caller will need to
154          * retry to make sure it cannot acquire before parking.
155          */
156         // 仔细想想,如果进入到这个分支意味着什么
157         // 前驱节点的waitstatus不等于-1和1,那也就是只可能是0,-2,-3
158         // 在我们前面的源码中,都没有看到有设置waitstatus的,所以每个新的node入队时,waitstatu都是0
159         // 用cas将前驱节点的waitstatus设置为node.signal(也就是-1)
160         compareandsetwaitstatus(pred, ws, node.signal);
161     }
162     return false;
163 }
164 
165 // private static boolean shouldparkafterfailedacquire(node pred, node node)
166 // 这个方法结束根据返回值我们简单分析下:
167 // 如果返回true, 说明前驱节点的waitstatus==-1,是正常情况,那么当前线程需要被挂起,等待以后被唤醒
168 // 我们也说过,以后是被前驱节点唤醒,就等着前驱节点拿到锁,然后释放锁的时候叫你好了
169 // 如果返回false, 说明当前不需要被挂起,为什么呢?往后看
170 
171 // 跳回到前面是这个方法
172 // if (shouldparkafterfailedacquire(p, node) &&
173 //                parkandcheckinterrupt())
174 //                interrupted = true;
175 
176 // 1. 如果shouldparkafterfailedacquire(p, node)返回true,
177 // 那么需要执行parkandcheckinterrupt():
178 
179 // 这个方法很简单,因为前面返回true,所以需要挂起线程,这个方法就是负责挂起线程的
180 // 这里用了locksupport.park(this)来挂起线程,然后就停在这里了,等待被唤醒=======
181 private final boolean parkandcheckinterrupt() {
182     locksupport.park(this);
183     return thread.interrupted();
184 }
185 
186 // 2. 接下来说说如果shouldparkafterfailedacquire(p, node)返回false的情况
187 
188 // 仔细看shouldparkafterfailedacquire(p, node),我们可以发现,其实第一次进来的时候,一般都不会返回true的,原因很简单,前驱节点的waitstatus=-1是依赖于后继节点设置的。
189 //intwaitstatus默认值为0,也就是说,我都还没给前驱设置-1呢,怎么可能是true呢,但是要看到,这个方法是套在循环里的,所以第二次进来的时候状态就是-1了。
190 
191 // 为什么shouldparkafterfailedacquire(p, node)返回false的时候不直接挂起线程:
192 // 如果 head后面的节点 if (ws > 0)这里有多个节点的waitstatus都为1,这里多次循环之后,node的prev指向了head,此时还需要挂起吗?当然是不需要了,下一次for循环,就能获取到锁了。

解锁操作

最后,就是还需要介绍下唤醒的动作了。我们知道,正常情况下,如果线程没获取到锁,线程会被 locksupport.park(this); 挂起停止,等待被唤醒。

// 唤醒的代码还是比较简单的,你如果上面加锁的都看懂了,下面都不需要看就知道怎么回事了
public void unlock() {
    sync.release(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;
}

// 回到reentrantlock看tryrelease方法
protected final boolean tryrelease(int releases) {
    int c = getstate() - releases;
    if (thread.currentthread() != getexclusiveownerthread())
        throw new illegalmonitorstateexception();
    // 是否完全释放锁
    boolean free = false;
    // 其实就是重入的问题,如果c==0,也就是说没有嵌套锁了,可以释放了,否则还不能释放掉
    if (c == 0) {
        free = true;
        setexclusiveownerthread(null);
    }
    setstate(c);
    return free;
}

/**
 * wakes up node's successor, if one exists.
 *
 * @param node the node
 */
// 唤醒后继节点
// 从上面调用处知道,参数node是head头结点
private void unparksuccessor(node node) {
    /*
     * if status is negative (i.e., possibly needing signal) try
     * to clear in anticipation of signalling.  it is ok if this
     * fails or if status is changed by waiting thread.
     */
    int ws = node.waitstatus;
    // 如果head节点当前waitstatus<0, 将其修改为0
    if (ws < 0)
        compareandsetwaitstatus(node, ws, 0);
    /*
     * thread to unpark is held in successor, which is normally
     * just the next node.  but if cancelled or apparently null,
     * traverse backwards from tail to find the actual
     * non-cancelled successor.
     */
    // 下面的代码就是唤醒后继节点,但是有可能后继节点取消了等待(waitstatus==1)
    // 从队尾往前找,找到waitstatus<=0的所有节点中排在最前面的一个
    node s = node.next;
    //如果头节点后面的第一个节点状态为-1,并没有被取消,是不会进入到下面的方法中
    if (s == null || s.waitstatus > 0) {
        s = null;
        // 从后往前找,仔细看代码,不必担心中间有节点取消(waitstatus==1)的情况
        for (node t = tail; t != null && t != node; t = t.prev)
            if (t.waitstatus <= 0)
                s = t;
    }
    if (s != null)
        // 唤醒线程
        locksupport.unpark(s.thread);
}

但是为什么要从后面开始遍历寻找waitstatus<=0的所有节点中排在最前面的一个,为什么不从前面的节点开始找呢?
这个问题的答案在 addwaiter(node mode)方法中,看下面的代码:

 1 node pred = tail;
 2     if (pred != null) {
 3         node.prev = pred;
 4         // 1. 先设置的 tail
 5         if (compareandsettail(pred, node)) {
 6             // 2. 设置前驱节点的后继节点为当前节点
 7             pred.next = node;
 8             return node;
 9         }
10 }

这里存在并发问题:从前往后寻找不一定能找到刚刚加入队列的后继节点。

如果此时正有一个线程加入等待队列的尾部,执行到上面第7行,第7行还未执行,解锁操作如果从前面开始找 头节点后面的第一个节点状态为-1的节点,此时是找不到这个新加入的节点的,因为尾节点的next 还未指向新加入的node,但是从后面开始遍历的话,那就不存在这种情况。

 

唤醒线程以后,被唤醒的线程将从以下代码中继续往前走:我们刚才是找到head后面第一个状态为-1的节点里面的线程进行唤醒

private final boolean parkandcheckinterrupt() {
    locksupport.park(this); // 刚刚线程被挂起在这里了
    return thread.interrupted();
}
// 又回到这个方法了:acquirequeued(final node node, int arg),这个时候,node的前驱是head了

此时第一个等待节点已经被唤醒,则第一个等待节点里面的线程继续执行 acquirequeued ,此时acquirequeued 方法中 85行处p已经是head节点了,94行处就可以继续尝试获取锁了。依次循环,这个节点获取到锁,解锁后,等待队列head节点后第一个节点进行唤醒获取锁。

 

总结

在并发环境下,加锁和解锁需要以下三个部件的协调:

  1. 锁状态。我们要知道锁是不是被别的线程占有了,这个就是 state 的作用,它为 0 的时候代表没有线程占有锁,可以去争抢这个锁,用 cas 将 state 设为 1,如果 cas 成功,说明抢到了锁,这样其他线程就抢不到了,如果锁重入的话,state进行+1 就可以,解锁就是减 1,直到 state 又变为 0,代表释放锁,所以 lock() 和 unlock() 必须要配对啊。然后唤醒等待队列中的第一个线程,让其来占有锁。
  2. 线程的阻塞和解除阻塞。aqs 中采用了 locksupport.park(thread) 来挂起线程,用 unpark 来唤醒线程。
  3. 阻塞队列。因为争抢锁的线程可能很多,但是只能有一个线程拿到锁,其他的线程都必须等待,这个时候就需要一个 queue 来管理这些线程,aqs 用的是一个 fifo 的队列,就是一个链表,每个 node 都持有后继节点的引用。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网