[size=medium]lock(), 拿不到lock就不罷休,不然執行緒就一直block。
lockinterruptibly會優先響應執行緒中斷,處理響應的方式是丟擲interruptedexception。[/size]
可以從原始碼看出來的
private void doacquireinterruptibly(int arg)
throws interruptedexception
if (shouldparkafte***iledacquire(p, node) &&
parkandcheckinterrupt())
throw new interruptedexception();
}} finally
}
可以看到這個有個 for (;;),會不斷去重試和檢查,如果有中斷就throw new interruptedexception()。
下面是個實際的例子:
public class lockinterruptiblytest
} class mythread implements runnable
catch (interruptedexception e)
} }
如果**是 lock.lock();
結果是:
thread-0 running
thread-1 running
(這裡休眠了5s)
thread-0 finished
thread-1 interrupted
如果**是 lock.lockinterruptibly();
結果是:
thread-1 running
thread-1 interrupted
thread-0 running
(這裡休眠了5s)
thread-0 finished
latch和lock的區別
latch是oracle提供的輕量級鎖資源,用於快速,短時間的鎖定資源,防止多個併發程序同時修改訪問某個共享資源,他只工作在記憶體中,我們可以不大準確的說,記憶體中資源的鎖叫latch,資料庫物件 表,索引等 的鎖叫lock。本文向各位闡述oracle的latch機制,latch,用金山詞霸翻譯是門...
synchronized和Lock的區別
lock提供了和synchronized類似的同步功能,只是在使用時需要顯示地獲取和釋放鎖,雖然lock缺少了synchronized隱士獲取釋放鎖的便捷性,但是卻擁有了鎖獲取與釋放的可操作性,可中斷的獲取鎖以及超時獲取鎖等多種synchronized所不具備的特性。雖然synchronized能夠...
Synchronized和Lock的區別
lock鎖一般通過使用reentrantlock 重入鎖 類進行使用,synchronized和lock鎖主要有以下幾點區別 1 synchronized是在jvm層面上實現的,通過在方法上加synchronized關鍵字或者將synchronized加在物件上實現加鎖,解鎖由jvm自動實現,ree...