class Test { public int i=1; public void test() { synchronized (this) { i++; } } }
//加一并返回值 public final int incrementAndGet() { for (;;) { int current = get(); int next = current + 1; if (compareAndSet(current, next)) return next; } } //返回CAS操作成功与否 public final boolean compareAndSet(int expect, int update) { //根据变量在内存中的偏移地址valueOffset获取原值,然后和预期值except进行比,如果符合,用update值进行更新,这个过程是原子操作 return unsafe.compareAndSwapInt(this, valueOffset, expect, update); }
public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); } // ReentrantLock的lock方法 public void lock() { sync.lock(); }
final void lock() { //如果当前同步状态为0(锁未被占有),CAS操作设置同步状态,设置成功的话当前线程获得锁(如果此时是公平锁,那么不会执行compareAndSetState方法,直接acuire排队) if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); //否则调用AQS的acquire方法 else acquire(1); } //CAS设置锁的状态 protected final boolean compareAndSetState(int expect, int update) { // See below for intrinsics setup to support this return unsafe.compareAndSwapInt(this, stateOffset, expect, update); }
//尝试获得锁,如果获取失败,将节点加入到尾节点 public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }
final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); //获取state变量值 int c = getState(); if (c == 0) { //如果没有线程占用锁 if (compareAndSetState(0, acquires)) { //设置当前线程获得锁 setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { //当前线程已经占用该锁 int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); // 更新state值为新的重入次数 setState(nextc); return true; } //获取锁失败 return false; }
private Node addWaiter(Node mode) { Node node = new Node(Thread.currentThread(), mode); // Try the fast path of enq; backup to full enq on failure Node pred = tail; //如果尾节点不为空 if (pred != null) { node.prev = pred; //此时可能同时有其他线程插入,再进行判断(通过CAS),如果没有,将节点设置为尾节点 if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } //如果节点为空或者节点不为空并且有其他线程插入(CAS返回false),执行enq方法 enq(node); return node; }
//通过自旋进行设置 private Node More enq(final Node node) { for (;;) { Node t = tail; if (t == null) { // Must initialize if (compareAndSetHead(new Node())) tail = head; } else { 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(); //获取前驱节点 //如果前驱是head尝试获锁 if (p == head && tryAcquire(arg)) { setHead(node); // 获取成功,将当前节点设置为head节点 p.next = null; // 原head节点出队 failed = false; return interrupted; //返回是否被中断过 } // 前节点不是头节点或者获取失败,判断是否可以挂起 if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) // 线程若被中断,设置interrupted为true interrupted = true; } } finally { if (failed) cancelAcquire(node); } }
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { //前驱节点的状态 int ws = pred.waitStatus; if (ws == Node.SIGNAL) // 前驱节点状态为signal(此节点线程结束后唤醒下一个节点线程) return true; //如果 前驱节点状态为CANCELLED(线程已经被取消) if (ws > 0) { // 删除cancelled状态的节点 do { node.prev = pred = pred.prev; } while (pred.waitStatus > 0); pred.next = node; } else { // 将前驱节点的状态设置为SIGNAL compareAndSetWaitStatus(pred, ws, Node.SIGNAL); } return false; }
private final boolean parkAndCheckInterrupt() { LockSupport.park(this); return Thread.interrupted(); }
我觉得分享是一种精神,分享是我的乐趣所在,不是说我觉得我讲得一定是对的,我讲得可能很多是不对的,但是我希望我讲的东西是我人生的体验和思考,是给很多人反思,也许给你一秒钟、半秒钟,哪怕说一句话有点道理,引发自己内心的感触,这就是我最大的价值。(这是我喜欢的一句话,也是我写博客的初衷)
原文链接:https://www.cnblogs.com/-new/p/7326820.html