ReentrantLock.lockInterruptibly允许在等待时由其它线程调用等待线程的Thread.interrupt方法来中断等待线程的等待而直接返回,这时不用获取锁,而会抛出一个InterruptedException。而ReentrantLock.lock方法不允许Thread.interrupt中断,即使检测到Thread.isInterrupted,一样会继续尝试获取锁,失败则继续休眠。只是在最后获取锁成功后再把当前线程置为interrupted状态。

那lockInterruptibly是如何做到这一点的?

   public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(
1);
    }


这里调用了AbstractQueuedSynchronizer.acquireInterruptibly方法。如果线程已被中断则直接抛出异常,否则则尝试获取锁,失败则doAcquireInterruptibly

 

 /**
     * Acquires in exclusive mode, aborting if interrupted.
     * Implemented by first checking interrupt status, then invoking
     * at least once {
@link #tryAcquire}, returning on
     * success.  Otherwise the thread is queued, possibly repeatedly
     * blocking and unblocking, invoking {
@link #tryAcquire}
     * until success or the thread is interrupted.  This method can be
     * used to implement method {
@link Lock#lockInterruptibly}.
     *
     * 
@param arg the acquire argument.  This value is conveyed to
     *        {
@link #tryAcquire} but is otherwise uninterpreted and
     *        can represent anything you like.
     * 
@throws InterruptedException if the current thread is interrupted
     
*/
    
public final void acquireInterruptibly(int arg) throws InterruptedException {
        
if (Thread.interrupted())
            
throw new InterruptedException();
        
if (!tryAcquire(arg))
            doAcquireInterruptibly(arg);
    }

相关文章:

  • 2021-11-29
  • 2021-10-14
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2021-06-16
  • 2022-01-09
  • 2021-11-25
猜你喜欢
  • 2021-10-07
  • 2021-06-17
  • 2022-12-23
  • 2021-07-18
  • 2021-11-23
  • 2021-04-11
  • 2021-08-15
相关资源
相似解决方案