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 

        

     

  • 相关阅读:
    【NOIP16提高组】换教室
    【扬中集训Day6T1】 白日梦
    【POJ 1061】 青蛙的约会
    【扬中集训DAY5T1】 交换矩阵
    【USACO】 Balanced Photo
    【USACO】 Balanced Lineup

    POJ P3352 Road Construction 解题报告
    洛谷 P2783 有机化学之神偶尔会做作弊 解题报告
    洛谷 P2300 合并神犇 解题报告
  • 原文地址:https://www.cnblogs.com/clarino/p/12833813.html
Copyright © 2011-2022 走看看