Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在哪种情况下保持中断状态?_Java_Multithreading_Threadpool - Fatal编程技术网

Java 在哪种情况下保持中断状态?

Java 在哪种情况下保持中断状态?,java,multithreading,threadpool,Java,Multithreading,Threadpool,我对捕捉InterruptedException但保留中断状态的情况很感兴趣,如下面的示例所示 try{ //Some code } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread

我对捕捉InterruptedException但保留中断状态的情况很感兴趣,如下面的示例所示

try{
    //Some code
    } catch (InterruptedException ie) {
         // (Re-)Cancel if current thread also interrupted
         pool.shutdownNow();
         // Preserve interrupt status
         Thread.currentThread().interrupt();
    }

如果需要调用方知道发生了中断,但无法更改方法签名以声明该方法
抛出InterruptedException
,则可以重新中断线程

例如,如果要实现
java.lang.Runnable
,则不能更改方法签名以添加选中的异常:

interface Runnable {
  void run();
}
因此,如果您在
Runnable
实现中执行了引发
InterruptedException
的操作,但无法处理该操作,则应在该线程上设置interrupted标志,以允许调用类处理该操作:

class SleepingRunnable implements Runnable {
  @Override public void run() {
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}

如果您能够更改方法签名,那么最好这样做:因为
InterruptedException
是一个选中的异常,所以调用方必须处理它。这使得您的线程可能会被中断的事实更加明显。

当您需要处理它时?这是一个很好的一般性描述,但是您的示例不是很好。在run方法的情况下,没有什么会关心线程是否被中断(当方法返回时,状态将被清除)。@jtahlborn您通常不知道这一点
Runnable.run()
可以在任何地方运行;您所说的只有在由线程或标准执行器实现运行时才是正确的。从技术上讲您是对的,但您多久调用一次Runnable而不是线程或执行器中的run?