lockInterruptibly和lock的区别

lock(), 拿不到lock就不罢休,不然线程就一直block。
lockInterruptibly会优先响应线程中断,处理响应的方式是抛出InterruptedException。


可以从源码看出来的

private void doAcquireInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.EXCLUSIVE);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }


可以看到这个有个 for (;;),会不断去重试和检查,如果有中断就throw new InterruptedException()。

下面是个实际的例子:
public class LockInterruptiblyTest {  
  public static void main(String[] args){  

      Thread i1 = new Thread(new MyThread());  
      Thread i2 = new Thread(new MyThread());  
      i1.start();  
      i2.start();  
      i2.interrupt();  
  }  

}  

class MyThread implements Runnable{  

  private static Lock lock = new ReentrantLock();  
  public void run(){  
      try{  
          System.out.println(Thread.currentThread().getName() + " running");  
          lock.lock(); 
//          lock.lockInterruptibly();   
          TimeUnit.SECONDS.sleep(5);  
          lock.unlock();  
          System.out.println(Thread.currentThread().getName() + " finished");  
      }  
      catch (InterruptedException e){  
          System.out.println(Thread.currentThread().getName() + " interrupted");  

      }  

  }  
}  



如果代码是 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

你可能感兴趣的:(interrupt)