此續文將介紹獨占模式下中斷獲取以及中斷超時獲取同步狀態的原理
1. LockSupport.park(Object blocker)
阻塞caller線程,注意這時線程狀態為Waiting而不是Blocked,所以并發包里凡是通過AQS來使線程等待的都是會使得線程變為Waiting狀態或者Time_Waiting狀態;LockSupport實現機制和Sychrongzied對象同步器機制不同,Object.norify/notifyAll并不會喚醒通過 LockSupport.park等待的線程。
image.png
這個方法遇到如下三種情況會讓LockSupport.park等待的線程喚醒返回
- Some other thread ** invokes unpark** with the current thread as the target;
- Some other thread interrupts the current thread;其他線程中斷此線程
- he call spuriously (that is, for no reason) returns.
所以當阻塞的線程發生中斷時會立刻從LockSupport.park返回
2. acquireInterruptibly
與acquire相同,但是該方法響應中斷,并拋出中斷異常
下面是方法詳解
acquireInterruptibly
注意第一步是先預判是否線程已經被中斷了,如果還沒有開始嘗試獲取鎖就已經被中斷了則直接重置中斷狀態并拋出中斷異常image.png
doAcquireInterruptibly
image.png
3. tryAcquireNanos
是帶有超時限制的acquireInterruptibly方法
下面是方法詳解
tryAcquireNanos
image.png
doAcquireNanos
image.png