摘要:如果一個調用已經出現了,這里只計數。為表示永不過期當為時,是相對于新紀元之后的毫秒。否則這個值就是超時前的納秒數。要解除阻塞的線程
await
調用sync.acquireSharedInterruptibly
public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); }
sync.acquireSharedInterruptibly
調用tryAcquireShared方法返回<0執行doAcquireSharedInterruptibly
public final void acquireSharedInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (tryAcquireShared(arg) < 0) doAcquireSharedInterruptibly(arg); }
tryAcquireShared
嘗試獲取共享鎖,獲取成功返回1,否則-1
protected int tryAcquireShared(int acquires) { return (getState() == 0) ? 1 : -1; }
doAcquireSharedInterruptibly
private void doAcquireSharedInterruptibly(int arg)throws InterruptedException { final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); //如果前一個node為隊頭,則通過tryAcquireShared嘗試獲取共享鎖 if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { //獲取到鎖執行 setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return; } } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) throw new InterruptedException(); } } finally { //產生異常執行 if (failed) cancelAcquire(node); } }
addWaiter
調用addWaiter方法把隊尾設置為當前node;如果隊尾為空或者設置失敗則調用enq方法
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; }
enq
調用enq方法隊尾為空則創建空的隊尾和隊頭,否則重新設置隊尾為當前node,設置成功返回。enq和addWaiter方法不同在于enq循環執行一定會執行成功,不存在失敗情況
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; } } } }
predecessor
調用predecessor方法獲取前一個node
final Node predecessor() throws NullPointerException { Node p = prev; if (p == null) throw new NullPointerException(); else return p; } static final int CANCELLED = 1; //取消 static final int SIGNAL = -1; //下個節點需要被喚醒 static final int CONDITION = -2; //線程在等待條件觸發 static final int PROPAGATE = -3; //(共享鎖)狀態需要向后傳播
shouldParkAfterFailedAcquire
獲取當前node的前一個note的線程等待狀態,如果為SIGNAL,那么返回true,大于0通過循環將當前節點之前所有取消狀態的節點移出隊列;其他狀時,利用compareAndSetWaitStatus使前節點的狀態為-1;如果是第一次await時ws狀態是0,多次await時ws狀態是0,最后肯定返回true
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) { int ws = pred.waitStatus; if (ws == Node.SIGNAL) return true; if (ws > 0) { do { node.prev = pred = pred.prev; } while (pred.waitStatus > 0); pred.next = node; } else { compareAndSetWaitStatus(pred, ws, Node.SIGNAL); } return false; }
parkAndCheckInterrupt
調用park并返回線程是否已經中斷
private final boolean parkAndCheckInterrupt() { LockSupport.park(this); return Thread.interrupted(); }
park
調用UNSAFE.park阻塞當前線程
public static void park(Object blocker) { Thread t = Thread.currentThread(); setBlocker(t, blocker); UNSAFE.park(false, 0L); setBlocker(t, null); }
setBlocker
在當前線程t的parkBlockerOffset位置設置blocker的引用
private static void setBlocker(Thread t, Object arg) { // Even though volatile, hotspot doesn"t need a write barrier here. UNSAFE.putObject(t, parkBlockerOffset, arg); }
UNSAFE.park
/** * 阻塞一個線程直到countDownunpark
出現、線程 * 被中斷或者timeout時間到期。如果一個unpark
調用已經出現了, * 這里只計數。timeout為0表示永不過期.當isAbsolute
為true時, * timeout是相對于新紀元之后的毫秒。否則這個值就是超時前的納秒數。這個方法執行時 * 也可能不合理地返回(沒有具體原因) * * @param isAbsolute true if the timeout is specified in milliseconds from * the epoch. * 如果為true timeout的值是一個相對于新紀元之后的毫秒數 * @param time either the number of nanoseconds to wait, or a time in * milliseconds from the epoch to wait for. * 可以是一個要等待的納秒數,或者是一個相對于新紀元之后的毫秒數直到 * 到達這個時間點 */ UNSAFE.park(false, 0L);
調用sync.releaseShared
public void countDown() { sync.releaseShared(1); }
releaseShared
執行tryReleaseShared成功后執行doReleaseShared
public final boolean releaseShared(int arg) { if (tryReleaseShared(arg)) { doReleaseShared(); return true; } return false; }
tryReleaseShared
更新state值為state-1,如果state新值為0返回true,否則false
protected boolean tryReleaseShared(int releases) { // Decrement count; signal when transition to zero for (;;) { int c = getState(); if (c == 0) return false; int nextc = c-1; if (compareAndSetState(c, nextc)) return nextc == 0; } }
doReleaseShared
只要等待隊列有數據,獲取隊頭等待狀態,隊頭狀態=-1其他node為等待時,則把隊頭等待狀態置為初始,且調用unparkSuccessor方法;隊頭狀態=0時,把隊頭狀態置為-3傳播到下一node
private void doReleaseShared() { /* * Ensure that a release propagates, even if there are other * in-progress acquires/releases. This proceeds in the usual * way of trying to unparkSuccessor of head if it needs * signal. But if it does not, status is set to PROPAGATE to * ensure that upon release, propagation continues. * Additionally, we must loop in case a new node is added * while we are doing this. Also, unlike other uses of * unparkSuccessor, we need to know if CAS to reset status * fails, if so rechecking. */ for (;;) { Node h = head; if (h != null && h != tail) { int ws = h.waitStatus; if (ws == Node.SIGNAL) { if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) continue; // loop to recheck cases unparkSuccessor(h); } else if (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) continue; // loop on failed CAS } if (h == head) // loop if head changed break; } }
unparkSuccessor
上面調用unparkSuccessor時,node的狀態已經更改為0,且node.next存在,執行unpark方法
private void unparkSuccessor(Node node) { /* * If status is negative (i.e., possibly needing signal) try * to clear in anticipation of signalling. It is OK if this * fails or if status is changed by waiting thread. */ int ws = node.waitStatus; if (ws < 0) compareAndSetWaitStatus(node, ws, 0); /* * Thread to unpark is held in successor, which is normally * just the next node. But if cancelled or apparently null, * traverse backwards from tail to find the actual * non-cancelled successor. */ Node s = node.next; if (s == null || s.waitStatus > 0) { s = null; for (Node t = tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } if (s != null) LockSupport.unpark(s.thread); }
unpark
unpark執行完之后是如何更改head的?
public static void unpark(Thread thread) { if (thread != null) UNSAFE.unpark(thread); }
UNSAFE.unpark
/** * Releases the block on a thread created by *park
. This method can also be used * to terminate a blockage caused by a prior call topark
. * This operation is unsafe, as the thread must be guaranteed to be * live. This is true of Java, but not native code. * 釋放被park
創建的在一個線程上的阻塞.這個 * 方法也可以被使用來終止一個先前調用park
導致的阻塞. * 這個操作操作時不安全的,因此線程必須保證是活的.這是java代碼不是native代碼。 * @param thread the thread to unblock. * 要解除阻塞的線程 */ UNSAFE.unpark(thread);
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/73338.html
摘要:在創建對象時,需要轉入一個值,用于初始化的成員變量,該成員變量表示屏障攔截的線程數。當到達屏障的線程數小于時,這些線程都會被阻塞住。當所有線程到達屏障后,將會被更新,表示進入新一輪的運行輪次中。 1.簡介 在分析完AbstractQueuedSynchronizer(以下簡稱 AQS)和ReentrantLock的原理后,本文將分析 java.util.concurrent 包下的兩個...
摘要:對于,我們僅僅需要關心兩個方法,一個是方法,另一個是方法。首先,我們來看方法,它代表線程阻塞,等待的值減為。首先,的源碼實現和大相徑庭,基于的共享模式的使用,而基于來實現。 前言 本文先用 CountDownLatch 將共享模式說清楚,然后順著把其他 AQS 相關的類 CyclicBarrier、Semaphore 的源碼一起過一下。 CountDownLatch CountDown...
摘要:相較于方法,提供了超時等待機制注意,在方法中,我們用到了的返回值,如果該方法因為超時而退出時,則將返回。的這個返回值有助于我們理解該方法究竟是因為獲取到了鎖而返回,還是因為超時時間到了而返回。 前言 系列文章目錄 CountDownLatch是一個很有用的工具,latch是門閂的意思,該工具是為了解決某些操作只能在一組操作全部執行完成后才能執行的情景。例如,小組早上開會,只有等所有人...
摘要:好了,繼續向下執行,嘗試獲取鎖失敗后,會調用首先通過方法,將包裝成共享結點,插入等待隊列,插入完成后隊列結構如下然后會進入自旋操作,先嘗試獲取一次鎖,顯然此時是獲取失敗的主線程還未調用,同步狀態還是。 showImg(https://segmentfault.com/img/remote/1460000016012541); 本文首發于一世流云的專欄:https://segmentfa...
閱讀 2905·2021-11-11 16:55
閱讀 952·2021-09-28 09:36
閱讀 3804·2021-09-22 15:22
閱讀 2232·2021-09-06 15:12
閱讀 1767·2021-08-19 10:55
閱讀 2895·2019-08-30 12:52
閱讀 502·2019-08-29 14:03
閱讀 1209·2019-08-29 12:27