锁的膨胀过程

预备知识CAS

硬件对并发的支持

模拟CAS操作

public class SimpleCAS {

    private Integer value;

    private synchronized int get(){
        return value;
    }
    private synchronized int compareAndSwap(int a, int b){
        int v = value;
        return v == a ? b : v;
    }
    class CasCounter{
        private SimpleCAS simpleCAS;
        private Integer getValue(){
            return simpleCAS.get();
        }
        private Integer increment(){
            Integer v;
            do {
                v = simpleCAS.get();
            }
            while (v != simpleCAS.compareAndSwap(v,  v + 1));
            return v + 1;
        }
    }
}

预备知识 公平锁&非公平锁

流程图

锁的膨胀过程-LMLPHP

关于队列如何设计和形成的

 1、AQS类设计的主要属性

private transient volatile Node head;/队首
private transient volatile Node tail;//队尾
private volatile int state;//锁状态标识

2、Node类的设计

static final class Node {
        volatile Node prev;
        volatile Node next;
        volatile Thread thread;
}

锁的膨胀过程-LMLPHP

04-06 04:41