zoukankan      html  css  js  c++  java
  • AQS源码阅读笔记(一)

    AQS源码阅读笔记

    先看下这个类张非常重要的一个静态内部类Node。如下:

      

    static final class Node {
        //表示当前节点以共享模式等待锁
        static final Node SHARED = new Node();
              //表示当前模式以独占模式等待锁
        static final Node EXCLUSIVE = null;
        
        //表示当前线程等待锁的动作被取消了(那么当前节点将会在下一次迭代节点的时候被踢出)
        static final int CANCELLED =  1;
        //表示当前节点处于挂起状态,如果当前节点的前一个节点释放了锁,那么当前节点将会被唤醒
        static final int SIGNAL    = -1;
        //(此处先不分析,后续在分析COnfition的时候再分析)
        static final int CONDITION = -2;
         //此处我们先不分析,后续在分析释放锁的时候分析
        static final int PROPAGATE = -3;    
         //当前节点的状态
         volatile int waitStatus;
    
        //指向当前节点前一个节点的引用
    	volatile Node prev;
        //指向当前节点后一个节点的引用  
            volatile Node next;
        //当前节点持有的线程
            volatile Thread thread;
        //当前节点以何种方式等待锁(它的取值,要么是SHARE,要么是EXCLUSIVE)
            Node nextWaiter;
        //当前线程是否以共享模式等待锁
            final boolean isShared() {
                return nextWaiter == SHARED;
            }
        //查找当前节点的前一个节点
            final Node predecessor() throws NullPointerException {
                Node p = prev;
                if (p == null)
                    throw new NullPointerException();
                else
                    return 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;
            }
        }    
    

      

      接着,我们再来看看AQS中的字段:

    	private transient volatile Node head;
    
      
            private transient volatile Node tail;
    
      
            private volatile int state;
    

      其中, node和tail分别表示头结点和尾节点,这两个字段是用来的保证同步队列原子入(出)队操作(具体后续在分析具体的实现类中说)。

      state在此处可以简单理解为加锁的次数(每次加锁,state + 1,每次释放锁, state - 1,当state = 0的时候,就表示没有线程持有锁 )。

    后续结合具体的实现类来分析各种加锁,解锁。

    
    

        

  • 相关阅读:
    python BeautifulSoup库的基本使用
    python操作RabbitMQ
    MySQL主从复制
    python字典与集合操作
    常见术语
    Mac下如何使用homebrew
    springboot整合freemarker
    Servlet与JSP概念理解
    slf4j-api、slf4j-log4j12以及log4j之间什么关系?
    使用nodeJs安装Vue-cli并用它快速构建Vue项目
  • 原文地址:https://www.cnblogs.com/bedlimate/p/8810893.html
Copyright © 2011-2022 走看看