ReentrantLock 实现:
我们主要看一下非公平锁的实现:
/** * Performs lock. Try immediate barge, backing up to normal * acquire on failure. */ final void lock() {
//cas 原子性操作,将state 状态改变为1 if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread());//返回true ,说明目前现在还没有线程进来,那么就将当前的线程标记为锁的线程 else
//否则的话,执行如下逻辑
acquire(1); }
执行如下方法(包含了主要的3个方法): tryAcquire addWaiter acquireQueued
public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }
protected final boolean tryAcquire(int acquires) {
//非公平锁实现 return nonfairTryAcquire(acquires); }
/** * Performs non-fair tryLock. tryAcquire is implemented in * subclasses, but both need nonfair try for trylock method. */ final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread();
//获取当前state 的值这个值表示当前锁被重入的次数 int c = getState(); if (c == 0) {
//如果=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; }
在线程未申请到锁的时候:会执行 addWaiter acquireQueued 这两个方法:
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;
//预先处理下,解决性能问题 if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } enq(node); return node; }
我们主要看一下如何将线程安全同步的加入到队列中: 如下典型的乐观锁的实现:cas +for 循环重试机制
private Node 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; } } } }
完成了加入队列的操作后接下来就是 acquireQueued 操作了
final boolean acquireQueued(final Node node, int arg) { boolean failed = true; try { boolean interrupted = false;
//循环阻塞 for (;;) { final Node p = node.predecessor();
//如果当前node 节点的上一个节点是head 以及state 状态=0 时候(有线程释放锁的时候) 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); } }
原创打造,多多指教