zoukankan      html  css  js  c++  java
  • 并发编程之ReentrantLock

    一、ReentrantLock的核心组成

    1、CAS

    2、abstract static class Sync extends AbstractQueuedSynchronizer  ---AQS  (双向链表)

    3、锁的类型

     4、 UNSAFE.park(false, 0L); 、 UNSAFE.unpark(thread);

    特点:

    1、单个线程,交替执行时与AQS队列无关

    二、加锁源码解读

    protected final boolean tryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        //获取线程状态
        int c = getState();
        if (c == 0) {
        //hasQueuedPredecessors 判断队列是否有排队的线程
        //compareAndSetState  底层CAS 
            if (!hasQueuedPredecessors() &&
                compareAndSetState(0, acquires)) {
                //加锁成功将exclusiveOwnerThread 设置为当前线程
                setExclusiveOwnerThread(current);
                return true;
            }
        }
      //当前来获取锁的线程 与 持有锁的线程比较,如果是同一个线程,则state累加 是一种重入的思想 重入锁
    else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; }

    1、由此可以看出当队列中没有线程的时候,整个加锁过程核心就是CAS ;队列中没有线程的场景单线程工作或者多线程交替执行

     2、竞争执行

    //入队操作
        private Node addWaiter(Node mode) {
            //创建当前线程Node节点对象
            Node node = new Node(Thread.currentThread(), mode);
            Node pred = tail;
            if (pred != null) {
                //node 入队
                node.prev = pred;
                if (compareAndSetTail(pred, node)) {
                    pred.next = node;
                    return node;
                }
            }
            enq(node);
            return node;
        }
        //AQS 队头元素 Thread=null
        private Node enq(final Node node) {
            for (;;) {
                Node t = tail;
                //初始化 时 AQS 队头 元素 Thread=null
                if (t == null) { // Must initialize
                    if (compareAndSetHead(new Node()))
                        tail = head;
                } else {
                    //将传入的node入队
                    node.prev = t;
                    if (compareAndSetTail(t, node)) {
                        t.next = node;
                        return t;
                    }
                }
            }
        }
    
    
        final boolean acquireQueued(final Node node, int arg) {
            boolean failed = true;
            try {
                boolean interrupted = false;
                for (;;) {
                    //获取当前节点的上一个节点
                    final Node p = node.predecessor();
                    //判断 p是不是头结点,自有  tryAcquire()并且自己再尝试拿一次锁(自旋)
                    if (p == head && tryAcquire(arg)) {
                        setHead(node);
                        p.next = null; // help GC
                        failed = false;
                        return interrupted;
                    }
                    //自旋后判断是不是需要park()
                    if (shouldParkAfterFailedAcquire(p, node) &&
                        parkAndCheckInterrupt())
                        interrupted = true;
                }
            } finally {
                if (failed)
                    cancelAcquire(node);
            }
        }
    
    
    
        private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
            //线程状态
            int ws = pred.waitStatus;
            if (ws == Node.SIGNAL)
                /*
                 * This node has already set status asking a release
                 * to signal it, so it can safely park.
                 */
                return true;
            if (ws > 0) {
                /*
                 * Predecessor was cancelled. Skip over predecessors and
                 * indicate retry.
                 */
                do {
                    node.prev = pred = pred.prev;
                } while (pred.waitStatus > 0);
                pred.next = node;
            } else {
                 // 将上一个节点pred的WS状态设置为 -1 (当前线程只能把上一个线程的ws状态设置为-1,因为他自己park()后,无法设置自己的WS=-1,所以他的WS=-1只能由下一个线程来设置)
                compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
            }
            return false;
        }
        //让当前线程阻塞 park()
        private final boolean parkAndCheckInterrupt() {
            LockSupport.park(this);
            return Thread.interrupted();
        }
  • 相关阅读:
    Quickuse.Ioc 快速应用.依赖注入组件
    Quickuse.Utility 快速应用.基础组件
    对System.ComponentModel.DataAnnotations 的学习应用
    C# List 转 Tree 公共方法
    C# 用Redis实现的分布式锁
    使用DbTableColumnWeb项目简要
    Application_Error VS OnException 遇到的坑
    在使用Intelligencia.UrlRewriter过程中 中文乱码问题
    C# MVC 页面静态化导致的问题
    关于.NetCore与.Netframework 对于DataSet的序列化与反序列化问题的探讨.
  • 原文地址:https://www.cnblogs.com/jalja365/p/13726464.html
Copyright © 2011-2022 走看看