zoukankan      html  css  js  c++  java
  • 【多线程】AQS及周边子类(重入锁、CountdownLatch等)

    一、抽象类AQS在JDK应用

             ReentrantLock、ReetrantReadWriteLock、

             Semaphore、CountDownLatch:Shared模式

             ThreadPoolExecutor

        

    二、AbstractQueuedSynchronizer

      Provides a framework for implementing blocking locks and related synchronizers (semaphores, events, etc) that rely on first-in-first-out (FIFO) wait queues.
      This class is designed to be a useful basis for most kinds of synchronizers that rely on a single atomic int value to represent state.
      Subclasses must define the protected methods that change this state, and which define what that state means in terms of this object being acquired or released. 

    2.1 对应的队列和state字段

      state=0代表当前并没有占用

        

          关于compareAndSetState实现:借助unsafe保证原子操作

            

    § 2.2 待子类实现

       

    § 2.2.1 实现排他模式Exclusive子类

       

    § 2.2.2 实现共享模式子类

       

    § 三、子类实现

            § 3.1 ReentrantLock

      1. 支持初始化是公平还是非公平
      2. 重入功能实现:
        1. tryAcquire(int acquires):识别当前getExclusiveOwnerThread()是自己,所以setState(getState() + acquire);
        2. tryRelease(int releases):将setState(getState() - releases)
          3)lock(): 通过acquire(1);首次场景,state=1,重入场景state++
          4)unlock(): state–;

            

        非公平核心实现

          如果state=0, 代表没有其他线程占用;直接(而不是由等待队列)尝试设置当前线程为排他线程,并设置state;
          如果state!=0,且自己为当前占用的线程,累加state

            

         公平Sync核心实现

          如果state=0,代表没有其他线程占用;由等待队列尝试设置当前线程为排他线程,并设置state;

           

        § 3.2 CountDownLatch

          1.内部类Sync重写 tryAccquireShared和tryReleaseShared,实现共享。
        2.countDownLatch(int count):最终调用AQS的setState(count)
                  3.countDown():最终调用AQS的state-1 

        

     

  • 相关阅读:
    参考资料
    利用docker compose启动gitlab及runner
    在gitlab上setup CI
    git ssh端口号变更之后所需要的修改
    使用Docker Image跑Gitlab
    用Docker Compose启动Nginx和Web等多个镜像
    .NET core mvc on Docker
    ubuntu 挂载windows共享目录的方法
    13-14 元旦随想
    Uva 10177 (2/3/4)-D Sqr/Rects/Cubes/Boxes?
  • 原文地址:https://www.cnblogs.com/clarino/p/12833813.html
Copyright © 2011-2022 走看看