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 

        

     

  • 相关阅读:
    MERGE引擎 分表后 快速查询所有数据
    MYSQL导入中文数据乱码的四种解决办法
    数据库中为什么不推荐使用外键约束?
    Word转PDF
    YII2 更新数据不成功
    YII2 使用curl请求,返回false
    Yii集成PHPWord
    网站安全DDOS攻击及监测
    nginx日志
    定时任务秒级执行
  • 原文地址:https://www.cnblogs.com/clarino/p/12833813.html
Copyright © 2011-2022 走看看