zoukankan      html  css  js  c++  java
  • ReentrantLock && AQS

    1. ReentrantLock 源代码

    使用AQS框架,CAS的操作代替了Synchronized里面的重量级锁, AQS里边维护一个队列,存储需要拿到资源的Thread

    a. ReentrantLock 内部类

    abstract static class Sync extends AbstractQueuedSynchronizer 

    nonfairTryAcquire

    tryRelease

    static final class NonfairSync extends Sync 

    static final class FairSync extends Sync

    b. 构造方法

    public ReentrantLock() {
        sync = new NonfairSync();
    }


    public ReentrantLock(boolean fair) {
         sync = fair ? new FairSync() : new NonfairSync();
    }

    c. 重点方法

    public void lock() {
      sync.lock();
    }

    public void unlock() {
      sync.release(1);
    }

    public void lockInterruptibly() throws InterruptedException {
      sync.acquireInterruptibly(1);
    }

    public boolean tryLock() {
      return sync.nonfairTryAcquire(1);
    }

    public boolean tryLock(long timeout, TimeUnit unit)
    throws InterruptedException {
      return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

    2. class AbstractQueuedSynchronizer

    a. 内部类 

    static final class Node

    public class ConditionObject 

    b. 变量

     private transient volatile Node head;

     private transient volatile Node tail;

    private volatile int state;

    c. 主要方法

    使用For去不断的循环查看前面的Node是Head,如果是,则试着获取锁,直到获取完锁才停止

  • 相关阅读:
    [转载]服务器管理模块forever——Nodejs中间件系列
    [转载]NodeJS的异步编程风格
    break和continue的区别?
    JavaScript中遍历数组的方法
    行盒
    雪碧图
    将一个块级元素水平和垂直居中的方法
    Linux使用rdesktop连接Windows桌面
    git常用操作
    TiddlyWiki搭建个人博客
  • 原文地址:https://www.cnblogs.com/Ivyduan/p/14627709.html
Copyright © 2011-2022 走看看