上面第一篇深入分析Lock(一)http://blog.csdn.net/h2482018/article/details/48715109,接下来继续往下面看,addWaiter;
先看下addWaiter的源码如下:
private Node addWaiter(Node node)
{
Node node1 = new Node(Thread.currentThread(), node);
Node node2 = tail;
if(node2 != null)
{
node1.prev = node2;
if(compareAndSetTail(node2, node1))
{
node2.next = node1;
return node1;
}
}
enq(node1);
return node1;
}
这个时候我们会看到有一个Node,Node是什么东西呢?我们得先看下Node这个对象;
static final class Node
{
final boolean isShared()
{
return nextWaiter == SHARED;
}
final Node predecessor()
throws NullPointerException
{
Node node = prev;
if(node == null)
throw new NullPointerException();
else
return node;
}
static final Node SHARED = new Node();
static final Node EXCLUSIVE = null;
static final int CANCELLED = 1;
static final int SIGNAL = -1;
static final int CONDITION = -2;
static final int PROPAGATE = -3;
volatile int waitStatus;
volatile Node prev;
volatile Node next;
volatile Thread thread;
Node nextWaiter;
Node()
{
}
Node(Thread thread1, Node node)
{
nextWaiter = node;
thread = thread1;
}
Node(Thread thread1, int i)
{
waitStatus = i;
thread = thread1;
}
}
看了Node的整个结构之后,我们明白,Node由这个这几个重要的成员变量
a:int waitStatus 表示节点的状态。其中包含的状态有:
- CANCELLED,值为1,表示当前的线程被取消;
- SIGNAL,值为-1,表示当前节点的后继节点包含的线程需要运行,也就是unpark;
- CONDITION,值为-2,表示当前节点在等待condition,也就是在condition队列中;
- PROPAGATE,值为-3,表示当前场景下后续的acquireShared能够得以执行;
- 值为0,表示当前节点在sync队列中,等待着获取锁。
c :Node next后继节点。
d :Node nextWaiter存储condition队列中的后继节点。
e :Thread thread入队列时的当前线程。
了解了Node的具体结构之后我们再来看addWaiter的方法,先初始化一个关于当前线程的的排它锁的类型的初始化对象,并且取得当前队列当中的队尾的node,如果node为空的,那么进入enq方法将node1放入队列当中去;
上图是表示一个我们的一个AQS,AQS有一个private transient Thread exclusiveOwnerThread;这个属性是来表示持有锁的线程,其他的线程这个时候是会被一次添加到队列的尾部去的,第一个节点是空节点,表示已经有线程持有了锁。enq方法就是在tail节点为空情况下将节点插入队列末尾的方法,如果tail节点不为空的那么利用CAS操作操作队列在队尾加入Node1;
那么我们回过头再看一下
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获取当前节点的前驱节点;
2判断当前节点的前驱节点是不是头结点并且能够获取到状态,那么将当前节点设置为sync队列的头结点(根据节点对锁占有的含义,设置头结点为当前节点。),并且将改前驱节点的后驱节点设置为null,用来帮助JVM进行垃圾回收,顺便提一下,JVM一般情况下都是根据GCRoot引用来的,而不是引用计数法;
3如果现在还没有轮到当前节点运行,那么把当前节点从线程调度器上面撤下来,也就是进入了等待状态;
我们要说的condition队列其实从某种意义上面来说是另一个sync队列,当然一个节点的线程执行完毕之后会先执行condition队列里面的节点对应的线程;