AbstractQueuedSynchronizer简单解析

来源:互联网 发布:android 查看端口占用 编辑:程序博客网 时间:2024/06/06 05:49

在JDK1.5版本,新增了并发包,其中包含了显示锁、并发容器。在这些锁和容器里,都有同步器(AQS)的身影。为了更好地理解JDK的并发包,我会用三个主题来详细描述AbstractQueuedSynchronizer的实现。

在AQS中,涉及到同步队列以及Condition对象,这也是我为什么要用三个主题来讲述的原因。本节将主要讲述同步队列,后面两节会分别讲述Condition对象以及AQS的主要功能实现。

AQS同步队列的主要功能是将无法获得资源的线程放入同步队列中,进行等待,它是通过链表来实现的,每一个节点对应一个任务线程。在AbstractQueuedSynchronizer类中用静态内部类Node来作为链表的数据结构。

static final class Node {/* 节点状态 */static final int CANCELLED =  1;static final int SIGNAL    = -1;static final int CONDITION = -2;static final int PROPAGATE = -3; /* 两种模式 */static final Node SHARED = new Node();static final Node EXCLUSIVE = null;/* 节点状态 */volatile int waitStatus;/* 模式 */Node nextWaiter;/* 前一个节点 */volatile Node prev;/* 后一个节点 */volatile Node next;/* 对应线程 */volatile Thread thread;/** * Returns true if node is waiting in shared mode */final boolean isShared() {    return nextWaiter == SHARED;}/** * Returns previous node, or throws NullPointerException if * null.  Use when predecessor cannot be null. * @return the predecessor of this node */final Node predecessor() throws NullPointerException {    Node p = prev;    if (p == null)throw new NullPointerException();    elsereturn p;}Node() {    // Used to establish initial head or SHARED marker}Node(Thread thread, Node mode) {     // Used by addWaiter    this.nextWaiter = mode;    this.thread = thread;}Node(Thread thread, int waitStatus) { // Used by Condition    this.waitStatus = waitStatus;    this.thread = thread;}    }

Node中有两个字段:waitStatus、nextWaiter。

对于nextWaiter,在同步队列中,该字段会用与模式的区分:SHARED(共享)、EXCLUSIVE(排他)。

对于waitStatus,取值可以是:SIGNAL、CANCELLED、CONDITION、PROPAGATE、0。

1、SIGNAL:后继节点将被或者已经被阻塞,所以当前节点在释放或者取消时,需要unpark它的后继节点。

2、CANCELLED:节点因为超时或者中断被取消。该状态不会再发生变,而且被取消节点对应的线程不会再发生阻塞。

3、CONDITION:该状态仅供在条件队列中的节点使用。当该节点转移到同步队列中时,该状态将被设置为0。

4、PROPAGATE:仅在共享模式下使用。在doReleaseShared()方法中,仅仅会设置头节点的状态为PROPAGATE。

5、0:除以上场景外的其他情况,状态均设置为0。

Node有两个构造方法:

1、在添加等待节点时,初始化线程和模式。

2、在添加条件队列的节点时,初始化线程和CONDITION状态。

以上就是Node的实现,后面的章节会继续介绍Node在AQS中的使用,敬请关注。



0 0