此續(xù)文將介紹獨(dú)占模式下中斷獲取以及中斷超時(shí)獲取同步狀態(tài)的原理
1. LockSupport.park(Object blocker)
阻塞caller線程捉片,注意這時(shí)線程狀態(tài)為Waiting而不是Blocked,所以并發(fā)包里凡是通過(guò)AQS來(lái)使線程等待的都是會(huì)使得線程變?yōu)閃aiting狀態(tài)或者Time_Waiting狀態(tài)罢绽;LockSupport實(shí)現(xiàn)機(jī)制和Sychrongzied對(duì)象同步器機(jī)制不同跟狱,Object.norify/notifyAll并不會(huì)喚醒通過(guò) LockSupport.park等待的線程。
這個(gè)方法遇到如下三種情況會(huì)讓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.
所以當(dāng)阻塞的線程發(fā)生中斷時(shí)會(huì)立刻從LockSupport.park返回
2. acquireInterruptibly
與acquire相同,但是該方法響應(yīng)中斷疆导,并拋出中斷異常
下面是方法詳解
acquireInterruptibly
注意第一步是先預(yù)判是否線程已經(jīng)被中斷了,如果還沒(méi)有開始嘗試獲取鎖就已經(jīng)被中斷了則直接重置中斷狀態(tài)并拋出中斷異常
doAcquireInterruptibly
3. tryAcquireNanos
是帶有超時(shí)限制的acquireInterruptibly方法
下面是方法詳解