调用LockSupport.parkNanos(long)后是否需要检查线程中断状态?

Is it necessary to check thread interrupted state after calling LockSupport.parkNanos(long)?

我的假设是 LockSupport.parkNanos(long) 不会抛出 InterruptedException,但可能会在线程上设置标志。

  1. 这是正确的吗?
  2. 如果是这样,我是否需要检查标志并抛出 InterruptedException

示例用法:

import java.util.concurrent.locks.LockSupport;

public void parkNanosInterruptibly(final long nanos)
throws InterruptedException {
    LockSupport.parkNanos(nanos);
    // If this thread was interrupted during parkNanos(), we must throw "by contract".
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }
}

是的,它不会抛出 InterruptedException。 Java文档

public static void parkNanos(long nanos)

Disables the current thread for thread scheduling purposes, for up to the specified waiting time, unless the permit is available. If the permit is available then it is consumed and the call returns immediately; otherwise the current thread becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes unpark with the current thread as the target;

  • or Some other thread interrupts the current thread;

  • or The specified waiting time elapses;

  • or The call spuriously (that is, for no reason) returns.

This method does not report which of these caused the method to return. Callers should re-check the conditions which caused the thread to park in the first place. Callers may also determine, for example, the interrupt status of the thread, or the elapsed time upon return.

Parameters: nanos - the maximum number of nanoseconds to wait

是的,忽视中断的事实是不正确的。所以你必须检查中断并以某种方式处理它(例如关闭一些资源并抛出异常或关闭线程或其他)。

Java 语言架构师 Brian Goetz http://www.ibm.com/developerworks/library/j-jtp05236/

中的一位发表了一篇好文章