• 【多线程】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 

        

     

  • 相关阅读:
    微软官方Silverlight5新特性完整介绍
    Windows Phone 7外包(承接WP7项目外包 可签合同 长期有效)
    我们为什么要选择Silverlight?(CSDN网友的见解分享大家)【转】
    开博记录02120928
    [转载]在linux下如何制作img的映像文件
    JavaScript中的null和undefined
    年度映像
    25岁毕业,拿一万块钱月薪
    saymedia bug问题
    mxp组件开发及jsfl文件
  • 原文地址:https://www.cnblogs.com/clarino/p/12833813.html
Copyright © 2020-2023  润新知