标签:手动 call nod 调用 gets tail depend vat max
1 /** 2 * Performs lock. Try immediate barge, backing up to normal 3 * acquire on failure. 4 */ 5 final void lock() { 6 if (compareAndSetState(0, 1)) 7 setExclusiveOwnerThread(Thread.currentThread()); 8 else 9 acquire(1); 10 }
1 protected final boolean tryAcquire(int acquires) { 2 return nonfairTryAcquire(acquires); 3 } 4 final boolean nonfairTryAcquire(int acquires) { 5 final Thread current = Thread.currentThread(); 6 int c = getState(); 7 if (c == 0) { 8 if (compareAndSetState(0, acquires)) { 9 setExclusiveOwnerThread(current); 10 return true; 11 } 12 } 13 //这里是为什么可重入的原因 14 else if (current == getExclusiveOwnerThread()) { 15 //判断当前线程是不是持有锁的线程,因为该线程在继续获取锁,那么直接将state变量值递增。 16 int nextc = c + acquires; 17 if (nextc < 0) // overflow 18 throw new Error("Maximum lock count exceeded"); 19 setState(nextc); 20 return true; 21 } 22 //未争抢到返回false 23 return false; 24 }
1 static final class FairSync extends Sync { 2 private static final long serialVersionUID = -3000897897090466540L; 3 //加锁的方法,直接调用acquire()方法继而调用自己实现的tryAcquire()方法 4 final void lock() { 5 acquire(1); 6 } 7 8 /** 9 * Fair version of tryAcquire. Don‘t grant access unless 10 * recursive call or no waiters or is first. 11 */ 12 protected final boolean tryAcquire(int acquires) { 13 final Thread current = Thread.currentThread(); 14 int c = getState(); 15 if (c == 0) { 16 //这里需要判断当前线程是不是在同步队列的队首 17 if (!hasQueuedPredecessors() && 18 compareAndSetState(0, acquires)) { 19 setExclusiveOwnerThread(current); 20 return true; 21 } 22 } 23 //这里的逻辑是和公平锁一样的,就是判断是不是当前线程是不是已经是获取到锁的线程,是的话将state变量值递增 24 else if (current == getExclusiveOwnerThread()) { 25 int nextc = c + acquires; 26 if (nextc < 0) 27 throw new Error("Maximum lock count exceeded"); 28 setState(nextc); 29 return true; 30 } 31 return false; 32 } 33 }
1 public final boolean hasQueuedPredecessors() { 2 // The correctness of this depends on head being initialized 3 // before tail and on head.next being accurate if the current 4 // thread is first in queue. 5 Node t = tail; // Read fields in reverse initialization order 6 Node h = head; 7 Node s; 8 return h != t && 9 ((s = h.next) == null || s.thread != Thread.currentThread()); 10 }
标签:手动 call nod 调用 gets tail depend vat max
原文地址:https://www.cnblogs.com/lgxblog/p/11704742.html