摘要:如果一個(gè)調(diào)用已經(jīng)出現(xiàn)了,這里只計(jì)數(shù)。為表示永不過(guò)期當(dāng)為時(shí),是相對(duì)于新紀(jì)元之后的毫秒。否則這個(gè)值就是超時(shí)前的納秒數(shù)。要解除阻塞的線(xiàn)程
await
調(diào)用sync.acquireSharedInterruptibly
public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); }
sync.acquireSharedInterruptibly
調(diào)用tryAcquireShared方法返回<0執(zhí)行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(); //如果前一個(gè)node為隊(duì)頭,則通過(guò)tryAcquireShared嘗試獲取共享鎖 if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { //獲取到鎖執(zhí)行 setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return; } } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) throw new InterruptedException(); } } finally { //產(chǎn)生異常執(zhí)行 if (failed) cancelAcquire(node); } }
addWaiter
調(diào)用addWaiter方法把隊(duì)尾設(shè)置為當(dāng)前node;如果隊(duì)尾為空或者設(shè)置失敗則調(diào)用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
調(diào)用enq方法隊(duì)尾為空則創(chuàng)建空的隊(duì)尾和隊(duì)頭,否則重新設(shè)置隊(duì)尾為當(dāng)前node,設(shè)置成功返回。enq和addWaiter方法不同在于enq循環(huán)執(zhí)行一定會(huì)執(zhí)行成功,不存在失敗情況
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
調(diào)用predecessor方法獲取前一個(gè)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; //下個(gè)節(jié)點(diǎn)需要被喚醒 static final int CONDITION = -2; //線(xiàn)程在等待條件觸發(fā) static final int PROPAGATE = -3; //(共享鎖)狀態(tài)需要向后傳播
shouldParkAfterFailedAcquire
獲取當(dāng)前node的前一個(gè)note的線(xiàn)程等待狀態(tài),如果為SIGNAL,那么返回true,大于0通過(guò)循環(huán)將當(dāng)前節(jié)點(diǎn)之前所有取消狀態(tài)的節(jié)點(diǎn)移出隊(duì)列;其他狀時(shí),利用compareAndSetWaitStatus使前節(jié)點(diǎn)的狀態(tài)為-1;如果是第一次await時(shí)ws狀態(tài)是0,多次await時(shí)ws狀態(tài)是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
調(diào)用park并返回線(xiàn)程是否已經(jīng)中斷
private final boolean parkAndCheckInterrupt() { LockSupport.park(this); return Thread.interrupted(); }
park
調(diào)用UNSAFE.park阻塞當(dāng)前線(xiàn)程
public static void park(Object blocker) { Thread t = Thread.currentThread(); setBlocker(t, blocker); UNSAFE.park(false, 0L); setBlocker(t, null); }
setBlocker
在當(dāng)前線(xiàn)程t的parkBlockerOffset位置設(shè)置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
/** * 阻塞一個(gè)線(xiàn)程直到countDownunpark
出現(xiàn)、線(xiàn)程 * 被中斷或者timeout時(shí)間到期。如果一個(gè)unpark
調(diào)用已經(jīng)出現(xiàn)了, * 這里只計(jì)數(shù)。timeout為0表示永不過(guò)期.當(dāng)isAbsolute
為true時(shí), * timeout是相對(duì)于新紀(jì)元之后的毫秒。否則這個(gè)值就是超時(shí)前的納秒數(shù)。這個(gè)方法執(zhí)行時(shí) * 也可能不合理地返回(沒(méi)有具體原因) * * @param isAbsolute true if the timeout is specified in milliseconds from * the epoch. * 如果為true timeout的值是一個(gè)相對(duì)于新紀(jì)元之后的毫秒數(shù) * @param time either the number of nanoseconds to wait, or a time in * milliseconds from the epoch to wait for. * 可以是一個(gè)要等待的納秒數(shù),或者是一個(gè)相對(duì)于新紀(jì)元之后的毫秒數(shù)直到 * 到達(dá)這個(gè)時(shí)間點(diǎn) */ UNSAFE.park(false, 0L);
調(diào)用sync.releaseShared
public void countDown() { sync.releaseShared(1); }
releaseShared
執(zhí)行tryReleaseShared成功后執(zhí)行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
只要等待隊(duì)列有數(shù)據(jù),獲取隊(duì)頭等待狀態(tài),隊(duì)頭狀態(tài)=-1其他node為等待時(shí),則把隊(duì)頭等待狀態(tài)置為初始,且調(diào)用unparkSuccessor方法;隊(duì)頭狀態(tài)=0時(shí),把隊(duì)頭狀態(tài)置為-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
上面調(diào)用unparkSuccessor時(shí),node的狀態(tài)已經(jīng)更改為0,且node.next存在,執(zhí)行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執(zhí)行完之后是如何更改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
創(chuàng)建的在一個(gè)線(xiàn)程上的阻塞.這個(gè) * 方法也可以被使用來(lái)終止一個(gè)先前調(diào)用park
導(dǎo)致的阻塞. * 這個(gè)操作操作時(shí)不安全的,因此線(xiàn)程必須保證是活的.這是java代碼不是native代碼。 * @param thread the thread to unblock. * 要解除阻塞的線(xiàn)程 */ UNSAFE.unpark(thread);
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/73338.html
摘要:在創(chuàng)建對(duì)象時(shí),需要轉(zhuǎn)入一個(gè)值,用于初始化的成員變量,該成員變量表示屏障攔截的線(xiàn)程數(shù)。當(dāng)?shù)竭_(dá)屏障的線(xiàn)程數(shù)小于時(shí),這些線(xiàn)程都會(huì)被阻塞住。當(dāng)所有線(xiàn)程到達(dá)屏障后,將會(huì)被更新,表示進(jìn)入新一輪的運(yùn)行輪次中。 1.簡(jiǎn)介 在分析完AbstractQueuedSynchronizer(以下簡(jiǎn)稱(chēng) AQS)和ReentrantLock的原理后,本文將分析 java.util.concurrent 包下的兩個(gè)...
摘要:對(duì)于,我們僅僅需要關(guān)心兩個(gè)方法,一個(gè)是方法,另一個(gè)是方法。首先,我們來(lái)看方法,它代表線(xiàn)程阻塞,等待的值減為。首先,的源碼實(shí)現(xiàn)和大相徑庭,基于的共享模式的使用,而基于來(lái)實(shí)現(xiàn)。 前言 本文先用 CountDownLatch 將共享模式說(shuō)清楚,然后順著把其他 AQS 相關(guān)的類(lèi) CyclicBarrier、Semaphore 的源碼一起過(guò)一下。 CountDownLatch CountDown...
摘要:相較于方法,提供了超時(shí)等待機(jī)制注意,在方法中,我們用到了的返回值,如果該方法因?yàn)槌瑫r(shí)而退出時(shí),則將返回。的這個(gè)返回值有助于我們理解該方法究竟是因?yàn)楂@取到了鎖而返回,還是因?yàn)槌瑫r(shí)時(shí)間到了而返回。 前言 系列文章目錄 CountDownLatch是一個(gè)很有用的工具,latch是門(mén)閂的意思,該工具是為了解決某些操作只能在一組操作全部執(zhí)行完成后才能執(zhí)行的情景。例如,小組早上開(kāi)會(huì),只有等所有人...
摘要:好了,繼續(xù)向下執(zhí)行,嘗試獲取鎖失敗后,會(huì)調(diào)用首先通過(guò)方法,將包裝成共享結(jié)點(diǎn),插入等待隊(duì)列,插入完成后隊(duì)列結(jié)構(gòu)如下然后會(huì)進(jìn)入自旋操作,先嘗試獲取一次鎖,顯然此時(shí)是獲取失敗的主線(xiàn)程還未調(diào)用,同步狀態(tài)還是。 showImg(https://segmentfault.com/img/remote/1460000016012541); 本文首發(fā)于一世流云的專(zhuān)欄:https://segmentfa...
摘要:中提供了幾個(gè)比較常用的并發(fā)工具類(lèi),比如。是一個(gè)同步工具類(lèi),它允許一個(gè)或多個(gè)線(xiàn)程一直等待,直到其他線(xiàn)程的操作執(zhí)行完畢再執(zhí)行。從命名可以解讀到是倒數(shù)的意思,類(lèi)似于我們倒計(jì)時(shí)的概念。 JUC中提供了幾個(gè)比較常用的并發(fā)工具類(lèi),比如CountDownLatch、CyclicBarrier、Semaphore。 其實(shí)在以前我們 課堂的演示代碼中,或多或少都有用到過(guò)這樣一些api,接下來(lái)我們會(huì)帶大家...
閱讀 2898·2021-11-11 16:55
閱讀 944·2021-09-28 09:36
閱讀 3794·2021-09-22 15:22
閱讀 2223·2021-09-06 15:12
閱讀 1754·2021-08-19 10:55
閱讀 2888·2019-08-30 12:52
閱讀 496·2019-08-29 14:03
閱讀 1204·2019-08-29 12:27