在捕获“InterruptedException”之后,为什么“Thread.currentThread()。isInterrupted()”的值为false?
作为标题。
public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); System.out.println(Thread.currentThread().isInterrupted()); //print false, who reset the interrupt? } } }); thread.start(); TimeUnit.SECONDS.sleep(1); thread.interrupt(); }
在捕获“InterruptedException”之后,为什么“Thread.currentThread()。isInterrupted()”的值为false?
从Javadoc for Thread.sleep
(由TimeUnit.sleep
调用):
InterruptedException – 如果有任何线程中断了当前线程。 抛出此exception时,将清除当前线程的中断状态。
我认为isInterrupted()
的目的是允许您在调用会抛出InterruptedException
之前检测线程是否已被InterruptedException
。 如果您已经捕获到 InterruptedException
,那么假设该线程已被中断是公平的……