以下代碼片段是https://leetcode.com/problems/print-in-order/的解決方案,它使用單個信號量運行printFirst.run()
、printSecond.run()
和。printThird.run()
三個執行緒 A、B 和 C 呼叫函式。執行緒 A 將呼叫first
,執行緒 B 將呼叫second
,執行緒 C 將呼叫third
。
我理解為什么由于 Java 將許可分配給佇列中的等待執行緒的方式,lock.acquire();
為什么lock.release();
需要在 中third
,而不是立即呼叫。lock.acquire(2);
呼叫lock.acquire(2);
會造成死鎖,因為沒有任何東西可以釋放足夠的許可。
話雖如此,我不明白在修復它之前如何lock.acquire();
遵循。lock.release();
有人可以向我解釋在first
第一次呼叫lock.release()
然后在運行之前third
呼叫的情況下會發生什么嗎?這是否會導致死鎖,就像單獨呼叫會導致死鎖一樣?這只是一種不太可能的情況,這就是為什么這樣做?lock.acquire(); lock.release(); lock.acquire(2);
second
lock.acquire(2);
對此的任何幫助將不勝感激,謝謝!
class Foo {
private Semaphore lock = new Semaphore(0);
public void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
lock.release();
}
public void second(Runnable printSecond) throws InterruptedException {
lock.acquire();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
lock.release(2);
}
public void third(Runnable printThird) throws InterruptedException {
lock.acquire();
lock.release();
lock.acquire(2);
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
uj5u.com熱心網友回復:
我現在明白為什么這是正確的并且不會死鎖。
擁有acquire()
and release()
before意味著acquire(2)
在third()
獲取時保證??許可數量為 1,這意味著second()
可以獲取并仍在進行中,或者second()
已經呼叫acquire()
并且有 0 個許可,但這并不重要,因為second()
大約to release(2)
,這將允許third()
繼續。
如果沒有acquire()
和release()
in third()
,則在其他執行緒third()
中acquire(2)
取得任何進展之前(即沒有許可并且second()
尚未成功獲取),這意味著釋放的許可first()
將繼續,third()
而第二個獲取將永遠不會成功。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/433432.html
上一篇:如何運行多個倒計時